Search code examples
c#unity-game-engineunitywebrequest

How to send UnityWebRequest POSTmethod with JSON param to a server using Unity


I'm trying to send a unitywebrequest

  var webRequest = UnityWebRequest.Post("https://example.com/api/auth/login","{\"username\": \"demo2\",\"password\": \"demo2\",\"password2\": \"demo2\"}");
  webRequest.SetRequestHeader("accept", "application/json");
  webRequest.SetRequestHeader("Content-Type", "application/json");
  webRequest.certificateHandler = new ForceAcceptAllCertificates();
  var operation = webRequest.SendWebRequest();

  while (!operation.isDone)
      await UniTask.Yield();

  responseCode = (HttpStatus)webRequest.responseCode;

  webRequest.certificateHandler.Dispose();
  webRequest.uploadHandler?.Dispose();

always I keep getting 400 error. What i'am do wrong

curl -X 'POST'
'https://example.com/api/auth/login'
-H 'accept: application/json'
-H 'Content-Type: application/json'
-d '{ "username": "demo", "password": "demo", "isLDAP": false }'


Solution

  • Besides the fact that your two JSON are quite different ;)

    From UnityWebRequest.Post with string, string parameters

    The data in postData will be escaped, then interpreted into a byte stream via System.Text.Encoding.UTF8. The resulting byte stream will be stored in an UploadHandlerRaw and the Upload Handler will be attached to this UnityWebRequest.

    You might rather want to use raw bytes and construct the request from scratch like e.g.

    var json = "{\"username\": \"demo2\",\"password\": \"demo2\",\"password2\": \"demo2\"}";
    var bytes = Encoding.UTF8.GetBytes(JSON);
    using(var webRequest = new UnityWebRequest(url, "POST"))
    {
        webRequest.uploadHandler = new UploadHandlerRaw(bytes);
        webRequest.downloadHandler = new DownloadHandlerBuffer();
        webRequest.certificateHandler = new ForceAcceptAllCertificates();
        webRequest.SetRequestHeader("accept", "application/json");
        webRequest.SetRequestHeader("Content-Type", "application/json");
    
        // Btw afaik you can simply
        await  webRequest.SendWebRequest();
    
        responseCode = (HttpStatus)webRequest.responseCode;
    }