【问题标题】:C# RestAPI CallC# Rest API 调用
【发布时间】:2020-02-09 12:16:32
【问题描述】:

我也是第一次尝试使用 C# 进行休息调用。 我认为我非常接近,但我收到一条错误消息:错误:400 - 错误请求。 这是我的代码:

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.test123.com/oauth2/token"))
    {

        string webstring = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id=${2}&client_secret={3}", access_code_string, RedirectURI,ClientId, ClientSecret);
        Console.WriteLine(webstring);
        request.Content = new StringContent(webstring);
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

        var response = await httpClient.SendAsync(request);
        Console.WriteLine("Access token: " + response);
    }
}

这是来自 Curl 的示例代码

curl -X POST \
    --header "Content-Type: application/x-www-form-urlencoded" \
    --data "grant_type=authorization_code&code=dlZE0KFxhM&redirect_uri=http%3A%2F%2Fclient%2eexample%2Ecom&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET"
    "https://api.test123.com/oauth2/token"

这是描述:

Obtain an access token
After you have received the authorization code you can request an access token.

Method
POST

URL
https://api.test123.com/oauth2/token

Request format
application/x-www-form-urlencoded

Request parameters
Name    Type    Description
grant_type  String  Value must be set to authorization_code
code    String  The authorization code
client_id   String  
client_secret   String  
redirect_uri    String  The URL where the response is sent. Must match the registered redirect URI.
Response format
application/json

【问题讨论】:

  • 你可能需要对webstring进行URL编码。
  • 得到错误:500 - 服务器错误:我尝试添加这个:string new_string = WebUtility.UrlEncode(webstring);
  • 我假设是在你格式化之后?使用 Fiddler 跟踪调用,并将发送的内容与您在 curl 中使用的内容进行比较。 500 错误可能表示服务器存在错误。
  • 我认为您应该使用参数构建 uri 字符串并使用此完整 url 创建请求。不传递内容。在这里您可以阅读有关构建网址的有用 api stackoverflow.com/questions/17096201/…
  • @Anton 是 POST,而不是 GET,格式定义为 application/x-www-form-urlencoded

标签: c# rest


【解决方案1】:

我采取了不同的方法

public void call()
    {

        string access_code_string = Read_Json_Values("accsess_code");
        string webstring = String.Format("https://api.test123.com/oauth2/token?grant_type=authorization_code&code={0}&client_id=${1}&client_secret={2}&redirect_uri={3}", access_code_string, ClientId, ClientSecret, RedirectURI);
        var client = new RestClient(webstring);
        client.Timeout = -1;
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddHeader("Authorization", "Bearer xxxx");
        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
        Console.WriteLine(response.Content);

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多