C# RestAPI Call - PullRequest
       4

C# RestAPI Call

0 голосов
/ 09 февраля 2020

Я тоже пытаюсь сделать повторный звонок с 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

1 Ответ

0 голосов
/ 09 февраля 2020

Я выбрал другой подход

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

    }
...