我是WPF的新手,并希望调用oauth令牌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个错误的请求。我的参数是:
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")));
我该如何解决?先感谢您。
您如何向邮递员进行身份验证?我在您的代码中看不到它。这取决于api的配置方式。确保在客户端调用中使用适当的auth方法,例如Bearer令牌。 Api应该返回400,而不是401。
httpClient.SetBearerToken(accessToken);