Unity3D - 向WWWForm添加自定义标头

Ja.*_*. L 1 c# unity-game-engine

这是我运行的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"]);
Run Code Online (Sandbox Code Playgroud)

如上所示,我尝试添加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)
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 5

WWWForm.headers变量是只读的.当你调用这个Add 函数时,它并没有真正添加任何东西.这就是为什么你得到这个错误,因为数据没有添加到WWWForm.headers.

Unity的WWW班级最近改变了.要添加标题,您必须创建Dictionary然后将其传递DictionaryWWW构造函数的第三个参数.

public WWW(string url, byte[] postData, Dictionary<string, string> headers);
Run Code Online (Sandbox Code Playgroud)

像这样的东西:

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);
Run Code Online (Sandbox Code Playgroud)

如果您有要发布的表单,则可以使用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);
Run Code Online (Sandbox Code Playgroud)