Unity3D - 向WWWForm添加自定义标头

时间:2017-06-15 22:31:13

标签: c# unity3d

以下是我运行的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)

1 个答案:

答案 0 :(得分:5)

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

Unity的WWW班最近有所改变。要添加标题,您必须创建Dictionary然后将Dictionary传递给WWW构造函数的第三个参数。

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);