HttpClient post 异步形式-url-编码和字符串内容不起作用
HttpClient post async form-url-encoded and string content not working
我正在尝试使用 System.Net.Http.HttpClient PostAsync 方法进行 api 调用。它在 await _httpClient.PostAsync(requestUri, stringContent);
之后永远挂起
HttpClient 配置:
_httpClient = new System.Net.Http.HttpClient(new HttpClientHandler
{
UseDefaultCredentials = WithDefaultCredentials,
AllowAutoRedirect = false
});
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATION_JSON));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApplicationXWwwFormUrlencoded));
if (!string.IsNullOrEmpty(CultureInfo.CurrentUICulture.Name))
{
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new
StringWithQualityHeaderValue(CultureInfo.CurrentUICulture.Name));
}
PostAsync 调用:
var stringContent = new StringContent(content);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(requestUri, stringContent);
var responseContent = await response.Content.ReadAsStringAsync();
使用 FormUrlEncodedContent 而不是字符串内容解决了我的问题:
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("username", username),
// ...
});
var response = await _httpClient.PostAsync(requestUri, requestContent);
var responseContent = await response.Content.ReadAsStringAsync();
我正在尝试使用 System.Net.Http.HttpClient PostAsync 方法进行 api 调用。它在 await _httpClient.PostAsync(requestUri, stringContent);
之后永远挂起HttpClient 配置:
_httpClient = new System.Net.Http.HttpClient(new HttpClientHandler
{
UseDefaultCredentials = WithDefaultCredentials,
AllowAutoRedirect = false
});
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATION_JSON));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApplicationXWwwFormUrlencoded));
if (!string.IsNullOrEmpty(CultureInfo.CurrentUICulture.Name))
{
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new
StringWithQualityHeaderValue(CultureInfo.CurrentUICulture.Name));
}
PostAsync 调用:
var stringContent = new StringContent(content);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(requestUri, stringContent);
var responseContent = await response.Content.ReadAsStringAsync();
使用 FormUrlEncodedContent 而不是字符串内容解决了我的问题:
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("username", username),
// ...
});
var response = await _httpClient.PostAsync(requestUri, requestContent);
var responseContent = await response.Content.ReadAsStringAsync();