Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnityWebRequest POST not sending Body

As the title says, the code is as below. I have tried setting chunkedTransfer=false, Content-Type application/json, WWWForm, building the JSON object manually, and HttpClient. For Content-Type application/json, the API isn't even hit. For the rest, the body is an empty object. I have no idea what the issue is here looking through StackOverflow, YouTube, Unity documentation, and all the other resources.

As of this morning I am using Newtonsoft.Json to serialize the JSON body. I think the biggest issue right now is that when I set webRequest.SetRequestHeader("Content-Type", "application/json"); the API route doesn't even receive the request.

async Task<string> makeRequest()
        {
            string url = API_BASE + "/users"; 
            
            Dictionary<string, string> body = new Dictionary<string, string>();
            body.Add("username", username);
            body.Add("password", password);
            body.Add("email", email);

            using (UnityWebRequest webRequest = UnityWebRequest.Post(url, JsonConvert.SerializeObject(body)))
            {
                await webRequest.SendWebRequest();

                string result = Encoding.UTF8.GetString(webRequest.downloadHandler.data);

                if (webRequest.result != UnityWebRequest.Result.Success)
                {
                    JSONNode error = JSON.Parse(result);

                    registerAndLoginError.GetComponent<Text>().text = error["error"]["message"];
                    registerAndLoginError.SetActive(true);

                    return "";
                }
            }

            BasicLogin();
            return "";
        }
like image 440
Rory L. Avatar asked Oct 21 '25 15:10

Rory L.


1 Answers

So I had seen this solution elsewhere, but I continued ignoring it because it's hacky af and seems like something that should be addressed. However, I'm at the point of not caring right now.

  1. Use UnityWebRequest.Put instead of UnityWebRequest.Post
  2. Set webRequest.method = "POST";
  3. Set webRequest.SetRequestHeader("Content-Type", "application/json");

This works, but it feels really bad and doesn't make any sense.

like image 54
Rory L. Avatar answered Oct 23 '25 05:10

Rory L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!