【发布时间】:2020-02-19 09:43:17
【问题描述】:
我是 WPF 新手,想调用 oauth token api 通过 HttpClient 获取经过身份验证的令牌。我已经尝试了很多解决方案,但仍然得到响应 Bad request(400)。
我也与邮递员核实过,api 工作正常。
postman response
尝试过的解决方案:
(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 bad request。
我的参数是:
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")));
我该如何解决?先感谢您。
【问题讨论】:
-
与邮递员核实,并检查您发送的数据字符串
-
@BugFinder 是的,我已经与邮递员核实过。在我的 api 中一切都很好。
-
@BugFinder 查看我的邮递员回复我已添加邮递员截图
-
在您的邮递员中,您在 3 个键之上发送了 9 个标头,其中有什么?
-
@BugFinder 只有一个 header 是 Content-Type 并且 value 是 application/x-www-form-urlencoded,其余的都是临时的
标签: c# wpf httpclient access-token