Как запросить OAuth-токен веб-API с помощью HttpClient в C # WPF? - PullRequest
0 голосов
/ 23 октября 2019

Я новичок в WPF и хочу вызвать oauth token api, чтобы получить аутентифицированный токен через HttpClient. Я пробовал много решений, но все еще получаю ответ. Плохой запрос (400).
Я также проверил с почтальоном, API работает нормально.
ответ почтальона

Пробные решения:
(1)

var request = new HttpRequestMessage(HttpMethod.Post, url);

request.Content = new FormUrlEncodedContent(param);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
request.Content.Headers.ContentType.CharSet = "UTF-8";

using (HttpResponseMessage response = await ApiHelper.apiClient.SendAsync(request))
{
    Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
    if (response.IsSuccessStatusCode)
    {
        //ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
        var responseString = await response.Content.ReadAsStringAsync();
        return response;
    }
    else
    {
        Console.WriteLine("postRequest -> exception -> " + response);
        throw new Exception(response.ReasonPhrase);
    }
}

(2)

using (var content = new FormUrlEncodedContent(param))
{
    content.Headers.Clear();
    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    using (HttpResponseMessage response = await ApiHelper.apiClient.PostAsync(url, content))
    {
        Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
        if (response.IsSuccessStatusCode)
        {
            //ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
            var responseString = await response.Content.ReadAsStringAsync();
            return response;
        }
        else
        {
            Console.WriteLine("postRequest -> exception -> " + response);
            throw new Exception(response.ReasonPhrase);
        }
    }
}

(3)

using (HttpResponseMessage response = await ApiHelper.apiClient.PostAsync(url, new FormUrlEncodedContent(param)))
{
    Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
    if (response.IsSuccessStatusCode)
    {
        //ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
        var responseString = await response.Content.ReadAsStringAsync();
        return response;
    }
    else
    {
        Console.WriteLine("postRequest -> exception -> " + response);
        throw new Exception(response.ReasonPhrase);
    }
}

Все решения отвечают мне 400 неверных запросов.
Мои параметры:

var params= new List<KeyValuePair<string, string>>();
            params.Add(new KeyValuePair<string, string>("grant_type", "password"));
            params.Add(new KeyValuePair<string, string>("username", HttpUtility.UrlEncode("myUsername")));
            params.Add(new KeyValuePair<string, string>("password", HttpUtility.UrlEncode("myPass")));

Как это исправить? Заранее спасибо.

Ответы [ 2 ]

0 голосов
/ 23 октября 2019

Oops! мой базовый URL начинается с http. Я забыл заменить его на https. Все нормально с https. :)
Спасибо

0 голосов
/ 23 октября 2019

Как вы проходите аутентификацию с почтальоном? Я не вижу этого в вашем коде. Это зависит от того, как настроен API. Обязательно используйте соответствующий метод auth при вызове клиента, например, токен Bearer. Api должен вернуть 400 вместо 401.

httpClient.SetBearerToken(accessToken);
...