I'm having trouble getting anything other than a 400 status from my webserver when using UnityWebRequest and json. Here's what I'm doing: Code (CSharp): //Example string param= "{"username":"aaa","app_key":"webGLTesting","password":"aaa"}"; UnityWebRequest CreateUnityWebRequest(string url, string param) { UnityWebRequest requestU= new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST); byte[] bytes= GetBytes(param); UploadHandlerRaw uH= new UploadHandlerRaw(bytes); uH.contentType= "application/json"; requestU.uploadHandler= uH; CastleDownloadHandler dH= new CastleDownloadHandler(); requestU.downloadHandler= dH; //need a download handler so that I can read response data return requestU; } class CastleDownloadHandler: DownloadHandlerScript { public delegate void Finished(); public event Finished onFinished; protected override void CompleteContent () { UnityEngine.Debug.Log("CompleteContent()"); base.CompleteContent (); if (onFinished!= null) { onFinished(); } } } protected static byte[] GetBytes(string str){ byte[] bytes = Encoding.UTF8.GetBytes(str); return bytes; } I can successfully hit my server, but it returns Status 400. I tried the same thing with the WWW class and it worked! The below is passed the exact same input string param as above. Code (CSharp): UnityEngine.WWW CreateUnityWebRequestV6(string url, string param) { Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Content-Type", "application/json"); byte[] body = Encoding.UTF8.GetBytes(param); UnityEngine.WWW www = new UnityEngine.WWW(url, body, headers); return www; } Also putting the json values in myself through form data also works with UnityWebRequest. Code (CSharp): UnityWebRequest CreateUnityWebRequestV3(string url, string param) { UnityEngine.WWWForm form = new UnityEngine.WWWForm(); form.AddField("username", "aaa"); form.AddField("password", "aaa"); form.AddField("app_key", "webGLTesting"); UnityWebRequest requestU= UnityWebRequest.Post(url, form); requestU.SetRequestHeader("Accept", "application/json"); requestU.uploadHandler.contentType= "application/json"; CastleDownloadHandler dH= new CastleDownloadHandler(); requestU.downloadHandler= dH; //need a download handler so that I can read response data return requestU; } I already have a working system using a preformated json string using JsonUtility and .Net. I would like to avoid rewriting everything and use form data. I am also assuming the WWW class is on the way out and want to use the newer UnityWebRequest. What am I doing wrong with UnityWebRequest and passing my byte[] into UploadHandlerRaw?
It's been about a month with this issue. I was simply using WWW, but with CORS WWW won't supply a status. I'm now back to looking at using UnityWebRequest. Anyone have ideas on why the byte[] won't work with UploadHandlerRaw?
Progress! I no longer get 400 errors. The issue was that the http request's content-type wasn't set. You'll notice in my original code below that I set the UploadHandlerRaw's content-type directly (line 5)... Code (CSharp): UnityWebRequest CreateUnityWebRequest(string url, string param) { UnityWebRequest requestU= new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST); byte[] bytes= GetBytes(param); UploadHandlerRaw uH= new UploadHandlerRaw(bytes); uH.contentType= "application/json"; //this is ignored? requestU.uploadHandler= uH; CastleDownloadHandler dH= new CastleDownloadHandler(); requestU.downloadHandler= dH; return requestU; } I thought my problem was setting the contentType too early. So I moved it after setting UnityWebRequest.upload handler, like below. Sadly, content-type was still ignored. Code (CSharp): UnityWebRequest CreateUnityWebRequest(string url, string param) { ... UploadHandlerRaw uH= new UploadHandlerRaw(bytes); requestU.uploadHandler= uH; uH.contentType= "application/json"; //this is also ignored. ... } Quite surprising considering Unity's documentation of UploadHandler.contentType: As you can see from my first code snippet, I never set a custom Content-Type header, so the uploadHandler.contentType should be honored. Anyways, setting request header manually DOES work. Code (CSharp): UnityWebRequest CreateUnityWebRequest(string url, string param) { ... UploadHandlerRaw uH= new UploadHandlerRaw(bytes); requestU.uploadHandler= uH; requestU.SetRequestHeader("Content-Type", "application/json"); ... } Hopefully this will help someone out there.
Thank you. I am currently trying to set up a Unity project with Django, but I had trouble sending a PUT request, receiving a HTTP 415 response (Unsupported Media Type). I also tried to create a new UploadHandlerRaw and attempted to set the uploadHandler.contenttype variable manually, then adding the uploadhandler to the UnityWebRequest object, however this action seemed to do no effect: Code (CSharp): UnityWebRequest webRequest = UnityWebRequest.Put(destination, formData); UploadHandler customUploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(formData)); customUploadHandler.contentType = "application/json"; webRequest.uploadHandler = customUploadHandler; SendRequest(webRequest); Setting the Content Type using the SetRequestHeader did the trick for me: Code (CSharp): UnityWebRequest webRequest = UnityWebRequest.Put(destination, formData); webRequest.SetRequestHeader("Content-Type", "application/json"); SendRequest(webRequest);
UnityWebRequest is so tied to MonoBehavior and mainthread so it is impossible to create a thread and let that handle the download/ upload. I'm baffled that the Unity-crew continue their development without any consideration for the more seasoned programmers out there. Furthermore they know about Microsoft .NET Core and the upcoming transition to .NET 4.6 and still they manage to produce such utterly crap. UnityWebRequest == WWW with new namespace.
Thanks @Freaking-Pingo for "SetRequestHeader." It made my Put / Post worked. Here is my put method: Code (CSharp): IEnumerator Post() { Building b = new Building { Id="1212", Name="InsertCoin.info", X= 000.1f }; string postData = JsonConvert.SerializeObject(b); byte[] bytes = GetBytes(postData); using (UnityWebRequest www = UnityWebRequest.Put("http://localhost:57459/api/building/?id=66", bytes)) { www.SetRequestHeader("Content-Type", "application/json"); yield return www.Send(); if (www.isError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); } } }
I recently tried this with the recent 5.6.1 stable. I have a working solution for POST/PATCH/PUT. You just need to ensure you're server supports the "X-HTTP-Method-Override" header. Also UnityWebRequest doesn't support PATCH out of the box for a true REST interface, this example does. Code (CSharp): UnityWebRequest request; switch (method) { case "POST": case "PATCH": // Defaults are fine for PUT case "PUT": byte[] bytes = Encoding.UTF8.GetBytes(requestBodyJsonString); request = UnityWebRequest.Put(url, bytes); request.SetRequestHeader("X-HTTP-Method-Override", method); break; case "GET": // Defaults are fine for GET request = UnityWebRequest.Get(url); break; case "DELETE": // Defaults are fine for DELETE request = UnityWebRequest.Delete(url); break; default: throw new Exception("Invalid HTTP Method"); } request.SetRequestHeader("accept", "application/json; charset=UTF-8"); request.SetRequestHeader("content-type", "application/json; charset=UTF-8"); Hope this helps people with the new upgrade to 5.6.1.
I manage to send the POST request and the response from my server is OK (200). However I don't manage to get the JSON on the server side. I did a check to see if content-type is "application/json" and it turns out the request's content-type is not recognized as "application/json". This prevents me from getting the json that I send from Unity. The API is written in PHP. Is there something else that we could add in the request? Did anyone else encounter the same or similar problem? Thanks! [UPDATE] I managed to solve my issue. After having tried different solutions as proposed above by @cogentEd, @ttesla and @dylan_shft I managed to set the content-type to 'application/json' and have it recognized as such by PHP. I had to assign uploadHandler's content type which I then assigned to the request's uploadHandler as proposed by @Freaking-Pingo - thx! For some reason setting the content type directly to UnityWebRequest did not work for me.
Hi guys! I am also try to upload file to server, but I don't know how to handle back end? Is there somewhere minimal example how to make it work? What I want to do is to upload json from unity and download from server (I want to be able to update data from unity and upload it to server and other clients to be able to download it from server) All I want is minimal example with one field in JSON and most simple back end part how it's done. There are a lot of sources on the web but complex for newbie Thanks!
This didn't work for me, I'm guessing my server doesn't support this override. However, I was able to get the above idea to work (hack the PUT into a POST) simply by doing this Code (CSharp): request.method = "POST"; instead of Code (CSharp): request.SetRequestHeader("X-HTTP-Method-Override", method);
Thank you very much, this one saved my day I wonder why in UnityWebRequest.Post there is no method overload to send simple binary data and we need this hack: Code (CSharp): byte[] bytePostData = Encoding.UTF8.GetBytes(postData); UnityWebRequest request = UnityWebRequest.Put(url, bytePostData); //use PUT method to send simple stream of bytes request.method = "POST"; //hack to send POST to server instead of PUT request.SetRequestHeader("Content-Type", "application/json"); For the sake of knoledge, the code above works with Spring Microservices too.
You can use WWWform form, and then form.AddBinaryData() for binary data. Then send the form with the UnityWebRequest.
I tried that, anyway it did not work with Spring microservice... Code (CSharp): byte[] byteArray = Encoding.UTF8.GetBytes(postData); WWWForm data = new WWWForm(); data.AddBinaryData("body", byteArray); UnityWebRequest request = UnityWebRequest.Post(url, data); request.method = "POST"; request.SetRequestHeader("Content-Type", "application/json"); Maybe I have to use something different from "body" in the data.AddBinaryData() ? Documentation does not explain parameter fieldName.. https://docs.unity3d.com/ScriptReference/WWWForm.AddBinaryData.html
I use this to upload images to my web server: CS: Spoiler Code (CSharp): IEnumerator UploadTextureTo(byte[] data, string filename, string md5) { Debug.Log("Image info: " + filename + ".jpg | byte size: " + data.Length.ToString()); WWWForm form = new WWWForm(); form.AddField("action", "save image"); form.AddField("sec", md5); form.AddField("folder", "MY-FOLDER-NAME"); form.AddField("filename", filename + ".jpg"); form.AddField("file", "file"); form.AddBinaryData("file", data, filename + ".jpg", "images/jpg"); UnityWebRequest uwr = UnityWebRequest.Post("MY-ROOT-URL" + "/" + "MY-PHP-SCRIPT.PHP", form); uwr.chunkedTransfer = false; //workaround for unity 2017.3 yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error: " + uwr.error); } else { if (uwr.uploadProgress == 1 && uwr.isDone) { yield return new WaitForSeconds(5); } } } PHP-File: Spoiler Code (CSharp): <?php header("Access-Control-Allow-Credentials: true"); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); header('Access-Control-Allow-Headers: Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time'); if ($_POST) { if ( isset ($_POST['action']) && isset ($_POST['folder']) && isset ($_POST['sec']) && $_POST['sec'] === md5($_POST['folder']."_MYSECURESTRING")) { if($_POST['action'] === 'save image') { if(!isset($_FILES) && isset($HTTP_POST_FILES)) { $_FILES = $HTTP_POST_FILES; } if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { if ($_FILES['file']['name'] !== "" && isset ($_POST['filename'])) { if ($_FILES['file']['type'] === 'images/jpg') { $uploadfile = $_FILES['file']['name']; $newimage = "Saves/" . $_POST['folder'] . "/" . $_POST['filename']; move_uploaded_file($_FILES['file']['tmp_name'], $newimage); } } } } } } ?>
For me the issue started happening in Unity 2017.3.1f1. For some reason UnityWebRequest didn't send Content-Length HTTP header until I set chunkedTransfer property to false. I think this is the related issue: https://issuetracker.unity3d.com/is...-to-get-content-length-header?page=2#comments
If you get 406 Not Acceptable I fixed it doing this. var headers = form.headers; Dictionary<string, string> ht = new Dictionary<string, string>(); ht["Accept"] = "*/*"; ht["Accept-Encoding"] = "gzip, deflate"; ht["User-Agent"] = "runscope/0.1"; ht["Content-Type"] = form.headers["Content-Type"].Replace("\"",""); WWW www = new WWW(url, form.data, ht); This is also a workaround to Generic/unknown HTTP error using UnityWebRequest.
I'm using 2017.3.1f1 and just yesterday I implemented some code that uploads JSON data to my server which handles it in PHP. It works fine - I don't get any issues (I'm only here because I was googling for using compression to send/receive data). This was tested both in Android and the Unity Editor run mode in x86. Here's my code: Code (CSharp): UnityWebRequest sendShowCall = new UnityWebRequest(url); sendShowCall.method = UnityWebRequest.kHttpVerbPOST; sendShowCall.timeout = userNetworkOpTimeout; sendShowCall.uploadHandler = new UploadHandlerRaw (dataToSend); sendShowCall.uploadHandler.contentType = "application/json"; Note that dataToSend is simply the JSON string converted to byte[] using System.Text.Encoding.UTF8 and before that a similar version of the code passing string also worked (but all the characters arrived escaped on the server). In fact, I have an entirely different version of this code using WWW which I did before whilst investigating this which also works fine (but has no timeout, hence why I use UnityWebRequest here).
I know this is an old thread... but this was the only thing that worked for me. And works like a charm!!!!
For me, I was missing the Download Handler, here is my code (requestData is an Object): string jsonString = JsonUtility.ToJson(requestData); Debug.Log("jsonString:" + jsonString); byte[] bytes = Encoding.UTF8.GetBytes(jsonString); using (UnityWebRequest www = new UnityWebRequest (URL)) { www.method = UnityWebRequest.kHttpVerbPOST; www.uploadHandler = new UploadHandlerRaw (bytes); www.downloadHandler = new DownloadHandlerBuffer (); www.uploadHandler.contentType = "application/json"; www.chunkedTransfer = false; yield return www.SendWebRequest (); if (www.isNetworkError || www.isHttpError) { Debug.Log (www.responseCode); Debug.Log (www.error); } else { Debug.Log ("Post complete! RespLength:" + www.downloadHandler.text.Length); Debug.Log ("text:" + www.downloadHandler.text); } }
when dealing with this issue I found this thread first, found a great solution on another thread so I am posting it here to make it more obtainable Code (CSharp): 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.SendWebRequest(); Debug.Log("Status Code: " + request.responseCode); } Original thread explaining why you have to build it yourself over using build in .post: https://forum.unity.com/threads/unitywebrequest-post-url-jsondata-sending-broken-json.414708/
hey folks, reviving the old thread. i need to upload bytes to a local webserver via MAMP as PNG files and i've tried a bunch of different methods and still getting errors. it completes with a 404 result. here's the code: Code (CSharp): IEnumerator UploadTextureTo(byte[] data, string filename) { Debug.Log("Image info: " + filename + " | byte size: " + data.Length.ToString()); WWWForm form = new WWWForm(); form.AddBinaryData("file", data, filename, "images/png"); UnityWebRequest uwr = UnityWebRequest.Post("http://localhost:8888/overviews/", form); uwr.method = "POST"; yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error: " + uwr.error); } else { if (uwr.uploadProgress == 1 && uwr.isDone) { yield return new WaitForSeconds(2); Debug.Log("Result:"+uwr.responseCode); } } } i tried putting the filename into the URL and it still results with a 404. it's been set to chmod 755 on the server, and i even went and changed the permissions in macOS. my byte[] has already been encoded as PNG before the coroutine is called. if i change the method to PUT i get 405 errors instead.
When the issue is in the client->server communication, instead of probing at the problem via C# code inside Unity, use the browser's Network tab to diagnose the issue: - https://developers.google.com/web/tools/chrome-devtools/network If the problem is a HTTP 404, it means the resource is not found. In that case, you'll need to check the server logs to figure out why the server is not serving the file from that URL. Is the URL wrong? Is the file misplaced on the server? Is something else wrong on the request? (server expects authentication, or is (mis)configured to behave in a specific manner with respect to certain request headers?) Server logs can help diagnose if there is something wrong with the server configuration.
well, i get that, but i'm able to operate a WebRequest that pulls an audio file from a similar folder on the same webserver via an AudioClip. so the location is virtually identical, it's just one is getting, and the other is putting or posting. but i'll check the browser and see if it's somehow a permissions issue for posting still.
SUCCESS! since there's a paucity of useful information on basic network uploading of binary data as PNG files that isnt 6-8 years old and using obsolete methods, let me share the basic facts (apologies if this is sounding remedial to most of you). first if you're using HTTP or UnityWebRequest to upload files to a webserver folder it absolutely needs a way to handle the upload requests at the server destination via a PHP script. this is not pointed out anywhere in the Unity documentation, and isn't intuitive since no such script is required to download the same data. here's an example script that just handles images that i got from a youtube tutorial: Code (CSharp): <?php if (isset($_FILES['uploadFile'])){ $img = $_FILES['uploadFile']['name']; $tmpimg = $_FILES['uploadFile']['tmp_name']; //to get file extension if needed //$fileExt = pathinfo($img,PATHINFO_EXTENSION); move_uploaded_file($tmpimg, "./overviews/$img"); echo "[success] image ($img) uploaded successfully"; exit(); } else{ echo "[error] there is no data with name [myimage]"; } ?> this is saved as index.php on a destination folder. successful uploads are moved into the './overviews' subfolder folder via the move_uploaded_file function. obviously permissions must be appropriately set on the folder. however you may have to configure the Apache webserver's httpd.conf file and make sure it's configured to use PHP. these lines are needed to add or uncomment (may have to be changed to reflect the version/s of PHP you plan to support): LoadModule php5_module libexec/apache2/libphp5.so AddHandler php5-script php finally, there's the Unity uploading script function, usually placed in a Coroutine. here's mine (thanks to the many posters on this thread and others): Code (CSharp): IEnumerator UploadTextureTo(byte[] data, string filename) { Debug.Log("Image info: " + filename + " | byte size: " + data.Length.ToString()); WWWForm form = new WWWForm(); form.AddBinaryData("uploadFile", data, filename, "images/png"); UnityWebRequest uwr = UnityWebRequest.Post("http://localhost:8888/overviews-upload/", form); uwr.method = "POST"; yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error: " + uwr.error); } else { if (uwr.uploadProgress == 1 && uwr.isDone) { yield return new WaitForSeconds(2); Debug.Log("Result:"+uwr.responseCode); } } } one last bit of information that may matter - the PHP script declares a generic string name for the upload itself. does not matter what it's called but it think it should match the Form data field (the first string in the form). so mine's called 'uploadFile' and that's declared in the WWWForm as well. i hope this helps newbie folks dealing with uploading binary data to webservers. just trying to update the information out there instead of 6-8 year old threads. a lot can change in that time. cheers!
It is unbelievable that Unity forcefully URL-encodes a POST body. I mean... why would anyone do this? I've been working in web backends for several years now and I've yet to encounter an URL encoded request body. Path params, query params? Sure, those come encoded. But the body? This seems extremely weird to me.
I am having a similar issue. 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: Code (CSharp): 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();
You might provide a valid JSON string in the request. You should provide double quotes instead of single quotes for each attributes with the help of the escape character ("\"). Try to change the methods as follows, Code (CSharp): public void Start() { string body = "{\"username\":\"" + _username + "\",\"password\",\"" + _password + "\"}"; //important StartCoroutine("localhost:3000/login", body)); } public IEnumerator Login(string url, string bodyJsonString) { UnityWebRequest request = new UnityWebRequest(url, "POST"); byte[] data = new System.Text.UTF8Encoding().GetBytes(bodyJsonString); // important request.uploadHandler = (UploadHandler) new UploadHandlerRaw(data); request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); // important yield return request.SendWebRequest(); if (request.isNetworkError) Debug.Log("Error While Sending: " + request.error); else Debug.Log("Received: " + request.downloadHandler.text); }
i used to have similar problem. The backend on the web server was done in a very strange way. I was forced to use such code. Code (CSharp): // First method (via old WWW) IEnumerator Login_v1() { // My json-string, written manually or received from any json-parser. string postData; // For example {"username":"MyName","password":"MyPass"} // Convert it to byte array!!! byte[] bytePostData = Encoding.UTF8.GetBytes(postData); // Make dictionary to hold some headers. Dictionary<string, string> headersDict = new Dictionary<string, string>(); // Add header to specify json-type data. headersDict.Add("Content-Type", "application/json"); // Send WWW request, using byte array and dictionary with headers. using (WWW www = new WWW(apiURL, bytePostData, headersDict)) { yield return www; Debug.Log(www.text); } } Code (CSharp): // Second method (via UnityWebRequest) IEnumerator Login_v2() { // My json-string, written manually or received from any json-parser. string postData; // For example {"username":"MyName","password":"MyPass"} // Convert it to byte array!!! byte[] bytePostData = Encoding.UTF8.GetBytes(postData); // The second parameter here will not be used anywhere. You just need to place there something. UnityWebRequest request = UnityWebRequest.Post(apiURL, postData); // Specify json-type data. request.SetRequestHeader("Content-Type", "application/json"); // Create an uploader for our web request. UploadHandlerRaw uploader = new UploadHandlerRaw(bytePostData); uploader.contentType = "application/json"; // This line can be omitted if you have already specified it via ' request.SetRequestHeader' // Replace default request uploader by new one. request.uploadHandler = uploader; yield return request.SendWebRequest(); Debug.Log(request.downloadHandler.text); } So the main idea of these methods are: - Pass in the request not a string, and not post-data, and not even WWWForm, but an array of bytes obtained from a json string - Specify the json data type in the request header May be my experience will help somebody to solve their problem.
I tried almost everything but not able to remove 400 error through my code plz help me out in this: var jsonObj = JsonUtility.ToJson(newUser); Debug.Log($"Json Object {jsonObj}"); byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonObj); UnityWebRequest request = UnityWebRequest.Put(posturi, bodyRaw); request.method = "POST"; request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { signUpTextWarning.text = request.error; Debug.Log(request.error); yield break; } else { Debug.Log(request.downloadHandler.text); } Debug.Log("Status Code: " + request.responseCode);
This is my code to Post data on my Post API but it's every times gives 400 error and almost every thing I tried to take reference from above code: var jsonObj = JsonUtility.ToJson(newUser); Debug.Log($"Json Object {jsonObj}"); byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonObj); UnityWebRequest request = UnityWebRequest.Put(posturi, bodyRaw); request.method = "POST"; request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { signUpTextWarning.text = request.error; Debug.Log(request.error); yield break; } else { Debug.Log(request.downloadHandler.text); } please help me to resolve this issue.