I need to send json data to a server that requires 2 parameters in a
application/x-www-form-urlencoded format where the second parameter is the json data.
I am porting an application from Xcode swift to Unity.
When the xcode app sends the data it is using a POST and the content type is set to application/x-www-form-urlencoded. When the server receives the data here is what it gets:
Parameters: {"access_token"=>"[FILTERED]", "json_data"=>[{"target"=>"120",
I cut off the rest of the data because the important part is there at the beginning of the json data for the json_data parameter.
I have tried several things including ideas from this thread and have my own UploadHandlerRaw and all that. When I look at www.uploadhandler.data and reencode it as a string this is what I get:
access_token=[FILTERED]&json_data=[{"target":120,
Looks like it should work, right? Well, when it gets to the server it looks like this:
access_token=[FILTERED]&json_data="[{\"target\":120,
It adds a leading double quote (") and slashes to all of the double quotes in the json data. Xcode doesn't do that.
So it looks like the UnityWebRequest component is url encoding where the xcode isn't even though the xcode code is using the same content-type value that I am using.
I have tried changing the content-type to application/json, but when I do then server doesn't know it is a form encoded input so it doesn't know how to get the 2 parameters. Only the parameter value for json_data is actually json, so the main content-type has to be x-www-form-urlencoded.
So how do I get the same behavior that xcode is giving? I need to use x-www-form-urlencoded as the content-type to pass 2 parameters to the POST, but the value of the second parameter needs to be the raw json data without a leading double quote and without the slashes in front of the the double quotes in the json data.
Here is my current implementation:
`
var raw = Encoding.UTF8.GetBytes($"access_token={AccessToken}&json_data={JSONData}");
UnityWebRequest www = new UnityWebRequest(APIURLPrefix + "/users/add_json_data", "POST");
www.SetRequestHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8");
www.uploadHandler = new UploadHandlerRaw(raw);
www.uploadHandler.contentType = "application/json";
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
`
↧