写 UnityWebRequest.Post 时出现问题

Problems writing a UnityWebRequest.Post

我不确定如何根据这些信息写出正确的 UnityWebRequest.Post :

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'

此请求的目的是获取令牌。我试过这样写请求:

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();

我收到错误 401,我真的不确定字段“Cookie”和“grant_type”。当我发送没有这些字段的请求时,我收到错误 400。

有人可以解释一下我应该如何执行此请求吗?

谢谢。

Headers != 表单域

您将获得 401

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

由于您将所有必需的身份验证 headers 作为 body 中的表单字段发送,因此您的请求缺少相应的 headers,因此未被授权。

如果没有 grant_type 数据字段,您将得到 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).

因为您没有发送任何数据。

Headers可以通过UnityWebRequest.SetRequestHeader

设置

您的请求可能更像是

// 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!");
    }
}