Unity3D – 向WWWForm添加自定义标头

这是我运行的C#代码:

WWWForm formData = new WWWForm (); //Adding formData.headers.Add ("Authorization", "Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes(CONSUMER_KEY + ":" + CONSUMER_SECRET))); formData.headers.Add ("Host", "api.twitter.com"); //Assigning formData.headers ["Host"] = "api.twitter.com"; formData.headers ["Authorization"] = "Basic " + System.Convert.ToBase64String (Encoding.UTF8.GetBytes (CONSUMER_KEY + ":" + CONSUMER_SECRET)); Debug.Log (formData.headers ["Authorization"]); 

如上所示,我尝试将AuthorizationHost字段添加到标题中,然后为了确定它们分配值。 但是Unity3D每次都会在formData.headers ["Authorization"]上抛出一个错误。

这是错误消息:

 KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary`2[System.String,System.String].get_Item (System.String key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150) Information+Twitter.GetToken () (at Assets/Static Libraries/Information.cs:143) Information.Initialize () (at Assets/Static Libraries/Information.cs:18) WorldScript.Awake () (at Assets/WorldScript.cs:16) 

WWWForm.headers变量是只读的。 当你调用Add函数时,它并没有真正添加任何东西。 这就是您收到该错误的原因,因为数据未添加到WWWForm.headers

Unity的WWW类最近发生了变化。 要添加标题,您必须创建Dictionary然后将该Dictionary传递给WWW构造函数的第三个参数。

 public WWW(string url, byte[] postData, Dictionary headers); 

像这样的东西:

 Dictionary headers = new Dictionary(); headers.Add("User-Agent", "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36"); WWW www = new WWW("http://www.thismachine.info/", null, headers); yield return www; Debug.Log(www.text); 

如果您有要发布的表单,可以使用WWWFormDictionary的组合来执行此操作。 只需使用WWWFormWWWForm转换为数组,然后将其传递给WWW构造函数的第二个参数。

 Dictionary headers = new Dictionary(); headers.Add("User-Agent", "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36"); WWWForm formData = new WWWForm(); formData.AddField("UserName", "Programmer"); formData.AddField("Password", "ProgrammerPass"); WWW www = new WWW("http://www.thismachine.info/", formData.data, headers); yield return www; Debug.Log(www.text);