繁体   English   中英

C# RestAPI 调用

[英]C# RestAPI Call

我也第一次尝试使用 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

我采取了不同的方法

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

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM