0

I am not sure how to write a correct UnityWebRequest.Post from these information :

curl --location --request POST 'https://url.com/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic UE5weXFUUUZjU1NTSkQ4eDFzQ0Fh' \
--header 'Cookie: ASP.NET_SessionId=qqjltxh; LSW_WEB=gatewaytraffic01; back_apim-tst_https=gateway-swarm-manager-03' \
--data-urlencode 'grant_type=client_credentials'

The point of this request is to get a token. I've tried writing the request like this :

WWWForm form = new WWWForm();
        form.AddField("Content-Type", "application/x-www-form-urlencoded");
        form.AddField("Authorization", "Basic UE5wzQ0Fh");
        form.AddField("Cookie" ,"ASP.NET_SessionId=qqjxh; LSW_WEB=gatewaytraffic01; back_apim-tst_https=gateway-swarm-manager-03");
        form.AddField("grant_type" ,"client_credentials");

        UnityWebRequest uwr = UnityWebRequest.Post("https://url.com/token", form);

        yield return uwr.SendWebRequest();

I get an error 401, i'm really not sure about the fields "Cookie" and "grant_type". When i send the request without those fields i get an error 400.

Could somebody explain how i should do this request ?

Thanks.

1 Answers1

0

Headers != Form field

You are getting a 401

UNAUTHORIZED
The request has not been applied because it lacks valid authentication credentials for the target resource.

Since you sent all the required authentication headers as form fields in the body thus your request is missing the according headers and is therefore not authorized.

Without the grant_type data field you get the 400

BAD REQUEST
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

since you didn't send any data.

Headers can be set via UnityWebRequest.SetRequestHeader

Your request should probably rather be something like

// Using this overload the Content-Type is automatically set to application/x-www-form-urlencoded
using(var uwr = UnityWebRequest.Post("https://url.com/token", "grant_type=client_credentials"))
{
    uwr.SetRequestHeader("Authorization", "Basic UE5wzQ0Fh");
    uwr.SetRequestHeader("Cookie" ,"ASP.NET_SessionId=qqjxh; LSW_WEB=gatewaytraffic01; back_apim-tst_https=gateway-swarm-manager-03");
    yield return uwr.SendWebRequest();

    // You should check for the results
    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log($"{www.responseCode} - {www.error}", this);
    }
    else
    {
        Debug.Log("Data upload complete!");
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115