Here is the C# Code I ran:
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"]);
As shown above, I tried to add Authorization
and Host
fields to the header and then Assigning them values just to be sure. However Unity3D throws a Error on formData.headers ["Authorization"]
everytime.
Here is the Error Message:
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)
The WWWForm.headers
variable is read only. When you call the Add
function, it's not really adding anything. That's why you are getting that error because the data is not added to the WWWForm.headers
.
Unity's WWW
class changed recently. To add headers, you have to create Dictionary then pass that Dictionary
to the third parameter of the WWW
constructor.
public WWW(string url, byte[] postData, Dictionary<string, string> headers);
Something like this:
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);
If you have form to post, you can use a combination of WWWForm
and Dictionary
to do that. Just convert the WWWForm
to array with WWWForm.data
then pass it to the second parameter of the WWW
constructor.
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);