2017-06-15 124 views
0

這裏是我跑的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) 

回答

3

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