消费API httpClient

问题描述 投票:0回答:1

我在尝试使用API​​时遇到错误“错误请求”。我尝试了一些不同的方法,但是没有成功。有人可以帮忙吗?

API参数必须为:

FormData参数

  1. scope =“ oob”
  2. grant_type =“ client_credentials”

标题参数

  1. 内容类型=“应用程序/ x-www-form-urlencoded”
  2. Authorization =“ Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI =”(以Base64为例)

[POST]

curl -X POST \https://api-sandbox.getnet.com.br/auth/oauth/v2/token\-H'授权:基本2xpZW50LTAxOnNlY3JldC1rZXktMDI ='\-H'内容类型:application / x-www-form-urlencoded'\-d'scope = oob&grant_type = client_credentials'

    string content_type = "application/x-www-form-urlencoded";
    string scope = "oob";
    string grant_type = "client_credentials";
    string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI="

    using (var httpClient = new HttpClient())
    {
         var requestMessage = new HttpRequestMessage()
         {
              Method = new HttpMethod("POST"),
              RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
              Content = new StringContent(
                            @"{""scope"":""oob"",""grant_type"":client_credentials}", Encoding.UTF8, content_type)};

          requestMessage.Content.Headers.ContentType = 
                new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

          requestMessage.Headers.Add("Authorization", authorization);

          var response = await httpClient.SendAsync(requestMessage);
          var responseStatusCode = response.StatusCode;
          var responseBody = await response.Content.ReadAsStringAsync();
    }
asp.net asp.net-core httpclient bad-request
1个回答
0
投票

您可以尝试遵循以下代码片段

  string content_type = "application/x-www-form-urlencoded";
  string scope = "oob";
  string grant_type = "client_credentials";
  string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=";

  using (var httpClient = new HttpClient())
  {
    var parameters = new List<KeyValuePair<string, string>>() {
      new KeyValuePair<string, string>("scope", "oob"),
      new KeyValuePair<string, string>("grant_type", "client_credentials")
    };

    var requestMessage = new HttpRequestMessage()
    {
      Method = new HttpMethod("POST"),
      RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
      Content = new FormUrlEncodedContent(parameters)
    };

    requestMessage.Content.Headers.ContentType =
          new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

    requestMessage.Headers.Add("Authorization", authorization);

    var response = await httpClient.SendAsync(requestMessage);
    var responseStatusCode = response.StatusCode;
    var responseBody = await response.Content.ReadAsStringAsync();
  }
© www.soinside.com 2019 - 2024. All rights reserved.