0

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 }'

derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

0

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;
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • thanks! One more question: if i using -> "using"construction: using(var webRequest = new UnityWebRequest(url, "POST")). thengad after request using Dispose methods webRequest.certificateHandler.Dispose(); webRequest.uploadHandler?.Dispose(); is not necessary? – Вячеслав М Nov 23 '22 at 08:25
  • @ВячеславМ Nope the `webRequest` will dispose these as well see [source code](https://github.com/Unity-Technologies/UnityCsReference/blob/70832e6c5b834ed12c9c19d91d6b710c55dfea67/Modules/UnityWebRequest/Public/UnityWebRequest.bindings.cs#L236) – derHugo Nov 23 '22 at 08:50