1
\$\begingroup\$

I am using C# to try retrieve a token and my code is based on this example:https://docs.unity3d.com/ScriptReference/WWWForm-headers.html

IEnumerator Start() {
  string urlToken = "myUrl";

  WWWForm form = new WWWForm ();
  form.AddField ("username", username);
  form.AddField ("password", password);

  Hashtable header = form.headers;//where I am getting my error*

  header.Add("content-type", "application/json"); //header I need send over


  WWW tokenRequest = new WWW (urlToken, form, header); 

  yield return tokenRequest;
  print ("Anything back?" + tokenRequest.bytesDownloaded);
}

*Assets/WWWDemo.cs(46,19): error CS0029: Cannot implicitly convert type System.Collections.Generic.Dictionary to System.Collections.Hashtable

How would the header be assigned correctly? Does anyone have any ideas?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

form.header is a Dictionary<string, string> - you need to do this

form.headers["content-type"] = "application/json";

or this (my preference)

var headers = form.headers;
headers["content-type"] = "application/json";

or this

Dictionary<string, string> headers = form.headers;
headers["content-type"] = "application/json";

Then your WWW constructor needs to be called like this

WWW tokenRequest = new WWW(urlToken, form.data, header);

because the 2nd parameter is a byte[] and not a Form (you missed that part out from the tutorial).

\$\endgroup\$
2
  • \$\begingroup\$ The first option removes the error in the question. Now the www object gives me error CS1502 when I pass it 3 arguments (new WWW (urlToken, form_1, form_1.headers)). Tried passing only two arguments, but my url won't accept either (I guess it doesn't see the needed header). \$\endgroup\$
    – BonnieB
    Commented Aug 5, 2016 at 7:08
  • \$\begingroup\$ I see the problem. I've updated my answer to include that too. \$\endgroup\$ Commented Aug 5, 2016 at 8:39
2
\$\begingroup\$

I have not tested it, but maybe you can try:

header["content-type"] = "application/json";

Anyway, as a note, if this is a real example; the content-type header is typically sent by the server, is not a request header

\$\endgroup\$
1
  • \$\begingroup\$ That's not accurate. When posting form data it is used to inform the server how the content was encoded. \$\endgroup\$ Commented Jan 31, 2017 at 14:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .