在C#中,我进行获取和发布请求。这是我的代码
获取
private async Task<string> GetAsync(string uri, Token token, string accept, string content_type)
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
bool added = client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/xml");
if (token != null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
HttpResponseMessage g = await client.GetAsync(uri);
if (g.IsSuccessStatusCode)
{
return await g.Content.ReadAsStringAsync();
}
else
{
errors.AddError(g.ReasonPhrase, await g.Content.ReadAsStringAsync());
return null;
}
}
开机自检
private async Task<string> PostAsync(string uri, Token token, string postData, string accept, string content_type)
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
if (token != null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var content = new StringContent(postData, Encoding.UTF8, content_type);
HttpResponseMessage g = await client.PostAsync(uri, content);
if (g.IsSuccessStatusCode)
{
return await g.Content.ReadAsStringAsync();
}
else
{
errors.AddError(g.ReasonPhrase, await g.Content.ReadAsStringAsync());
return null;
}
}
但是我读到你应该像这样重用httpclient
private static HttpClient client = new HttpClient();
我经常提出很多要求。但是,如果我重新使用该对象,则标题之类的设置仍然存在,并且会引起问题。有什么方法可以重置设置但保留对象吗?
谢谢
答案 0 :(得分:2)
不要使用HttpClient的默认标头。在请求上设置标题:
var content = new StringContent(postData, Encoding.UTF8, content_type) // CONTENT-TYPE header
content.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
if (token != null)
content.Headers.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
然后所有线程可以在应用程序的整个运行期间使用相同的HttpClient,而不会出现问题。