UnityWebRequest.Post(url, jsonData) sending broken Json

I’m doing the following: (Don’t worry it will be over HTTPS)

 UnityWebRequest.Post(url,jsonData)

The json data is as follows: {"username":"some username","password":"some password"}
The data is actually of type JsonObject but I’ve tried passing it as a string too.

When using PostMan tool in Chrome and sending this data it was processing correctly.

When sending via Unity I get additional data that fails Json linter:

 { '{"translationKey":"","username":"","password":""}': '' }

I have tried manually stripping the code; but I’d rather be sending safe json to begin with.

I’m using Express with NodeJS.

Can someone tell me what I’m doing wrong?

** Edit **

I’m using JsonUtility.ToJson(jsonData) to parse the data

Example of Json class:

public class JsonObjectNewUser : JsonObjectBase {

    public string username;
    public string password;

    public JsonObjectNewUser(string username, string password) {
        this.username = username;
        this.password = password;
    }
}

BaseJson

[System.Serializable]
publicclassJsonObjectBase{
    publicstringtranslationKey="";
}

Logging JsonUtility.ToJson(jsonObject) produces the correct json:

{
    "translationKey": "",
    "username": "",
    "password": ""
}

So something is being added in UnityWebRequest.Post…

I figured this out; use Put request and make sure the content header is set.

Example

var jsonString = JsonUtility.ToJson(jsonData) ?? "";
UnityWebRequest request = UnityWebRequest.Put(url, jsonString);
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
4 Likes

I stumbled upon this same issue. I can’t get the POST method to work with JSON, but I can get it to work with PUT.

1 Like

I dont have any trouble with post, what version of unity are you using?

Im using the wwwform for sending data to server. I only use Jsonutility when i get data from my server.

I can also use POST with WWWForm. It is using POST where data is JSON formatted and Content-Type is set to application/json.

UnityWebRequest is a very poor implementation of an HTTP client.

This might be your problem, depending on what is consuming your request: For some reason UnityWebRequest applies URL encoding to POST message payloads. URL encoding the payload is an ASP.NET webform thing. It is not part of the HTML standard (and if it were, it still shouldn’t matter to an HTTP client), and it certainly is not part of the HTTP standard.

To get an unmangled-POST through, create UnityWebRequest as a PUT, then in your own code change the Method property to POST after the fact.

Also note that if your RESTful API requires message payloads on GET requests (rare, but it happens, typically as part of sending complex search parameters) you’ll either have to change the API or find an alternative to UnityWebRequest. It will simply discard the message body if you change the method to GET. (Note I haven’t confirmed it’s the GET that discards the body; I also set Content-Type and that may trigger it too, I stopped caring about the specifics after I realized it was blindly throwing away my data.)

Error handling is also a mess. There is no comprehensive list of the errors the class itself can return and they’re just raw text strings. Server response is available strictly as the numeric response status code (annoyingly expressed as longs which means you have to remember to test against “200L” for OK, for example), and UnityWebRequest does not expose the response status description text, which means it throws away potentially useful error messages.

Oh yeah, it also won’t allow an empty message body on a POST or PUT operation, which is also stupid and not to HTTP spec.

There are open feedback items for most of these. Upvotes would be appreciated. I don’t have much hope they’ll fix it, though. In another thread a Unity dev started to argue about these, then bailed on the thread entirely. Other threads about these issues have been ignored (or maybe were not noticed in all the other traffic, no way to know for sure).

Right now I’m pondering whether to break my REST API to accomodate this mess, or ditch UnityWebRequest for some as-yet-unknown alternative, but I need the coroutine/yield async model and I haven’t dug into doing that DIY yet. Extremely frustrating.

18 Likes

Today I used that code and now it is working perfectly:

    IEnumerator Post(string url, string bodyJsonString)
    {
        var request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
        request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.Send();

        Debug.Log("Status Code: " + request.responseCode);
    }

Source: UnityWebRequestでjsonをpostしたい. #Unity5.3 - Qiita

Edit (2020):
It has already some time I don’t use the POST method in my projects, but I know that Unity changed a little bit the UnityWebRequest and added a new method only for Post. Here you are the Documentation about it:

28 Likes

I am currently using UnityWebRequest for our REST api, and I find it easy to use, and haven’t stumbled upon that many issues. Could you pleas link to the open feedback requests?

I am using UnityWebRequest example from here: Unity - Manual: Sending a form to an HTTP server (POST)
using our https url and although I get upload completed there server receives nothing.

I also note from that site that webform is legacy and UnityWebRequest is the ‘new’ way of doing it…but not if it does not work?

@elpuerco63_1 ,
Have you tried use this?

3 Likes

Oddly Unity has two different ways? I found that this version they supply works?

https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html

Yes, there are two ways:
UnityWebRequest.Post(url, form);
and
new UnityWebRequest(url, “POST”);

I believe it required a php on http server in order to use UnityWebRequest.Post() or UnityWebRequest.Put successfully?
I’m trying to use UnityWebRequest.Put to upload player data in jason to http server and overwrite its .txt but I’m very new to this category and having 0 experience on php scripting, does anyone have some reference .php codes I could learned from?

First of all, you need to learn how to code a “PHP Rest API” system that will receive data as Json and later manage the data to write in your .txt file. But maybe it will be better if instead of a .txt file, you save the data in a MySQL database.

Just search for “PHP Rest API” tutorials and you will learn it after some time of study.

You can use a good tool to test your PHP system before code in Unity:
https://www.getpostman.com/apps

After your PHP system is done, you can go to Unity and implement your “UnityWebRequest.Post”.

1 Like

Worked like a charm for me.
This is how my JsonString looked like:
"{
‘email’: ‘*****@test.de’,

‘password’: ‘*****’
}"

I want to send some video data to servers and want to show upload progress in android using unity web request
This html code is working, URL is working, please give me some example to achieve in unity android

Video :

Thanks, you’ve save my time

this should be starred / stickied / favorited everywhere - headache cured. will keep the other bits of your reply in mind as well, cheers!

The other alternative is to manually encode your JSON string to byte array and feed that.

Would there be a way to make this work, if we needed to provide image data as a base64 string?