After checking out a bunch of pages on how to post xml and json using WWWForm, I just cannot get a valid response from the server. It always gives me an error code 500.
The following curl command structure works:
curl --verbose --request POST --header "Content-Type: text/json" --data @newScore.json [url]https://myurl[/url]
newScore.json looks something like this:
{ score:1000, nickname:"nn" }
Please can someone help me get this into a JS script? Here’s what I have so far…
var postScoreURL = "https://myurl";
var jsonString = "{ score:1000, nickname:\"nn\" }";
var encoding = new System.Text.UTF8Encoding();
var postHeader = new Hashtable();
postHeader.Add("Content-Type", "text/json");
postHeader.Add("Content-Length", jsonString.Length);
print("jsonString: " + jsonString);
var request = WWW(postScoreURL, encoding.GetBytes(jsonString), postHeader);
yield request;
// Print the error to the console
if (request.error != null)
{
Debug.Log("request error: " + request.error);
}
else
{
Debug.Log("request success");
Debug.Log("returned data" + request.data);
}
It prints out “request success” but the server responds the data contains an error 500. Can anyone help please? The curl command works, so the server seems to be ok…
So actually this script works. I removed the Content-Length line but the problem I was having was an incorrect key value in my actual data that was failing a check on the server.
Parsing the json returned is another matter but there are posts already with answers on that topic.
What the heck - here’s how I got the info out using MiniJSON:
var requestString : String = "{\"status\":201,\"someKey\":\"someValue\"}";
var jsonKeys : Hashtable = MiniJSON.JsonDecode(requestString);
for(key in jsonKeys.Keys)
{
Debug.Log("key: " + key);
Debug.Log("value: " + jsonKeys.Item[key]);
}
print("status: " + jsonKeys.Item["status"]);
prints:
someKey
someValue
status
201
status: 201
Stick the MiniJSON C# script in a folder called “Standard Assets” (just create the folder if not already there). That way it will be compiled before the other scripts to allow usage from within your javascript scripts.
Hopefully this gives a decent explanation of how to do all this now
Just check your input data in your json string. Maybe “score” or “nickname” is not set in your server. Maybe its “username” instead of “nickname” or something like that.