Unity3D - 添加自定义标题,以WWWForm

Unity3D - 添加自定义标题,以WWWForm

问题描述:

这里是我跑的C#代码:Unity3D - 添加自定义标题,以WWWForm

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传递给构造函数的第三个参数。

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

事情是这样的:

Dictionary<string, string> headers = new Dictionary<string, string>(); 
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组合来做到这一点。只需将WWWForm转换为WWWForm.data然后将其传递给WWW构造函数的第二个参数。

Dictionary<string, string> headers = new Dictionary<string, string>(); 
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); 
+0

奇怪的是,改变一个只读对象不会给我一个错误或警告。 –

+0

我知道它是有线的。每次访问WWWForm.headers时,您都会得到一个新的Dictionary /副本,或者Unity有一个代码可以从“Dictionary”中删除任何内容。除非我有源代码,否则我无法分辨究竟发生了什么。 – Programmer