gpt4 book ai didi

c# - Unity3D - 将自定义 header 添加到 WWWForm

转载 作者:太空宇宙 更新时间:2023-11-03 19:46:46 25 4
gpt4 key购买 nike

这是我运行的 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 字段添加到 header ,然后为它们分配值以确保安全。然而,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 类最近发生了变化。要添加 header ,您必须创建 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);

关于c# - Unity3D - 将自定义 header 添加到 WWWForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com