![](/img/trans.png)
[英]How to set an HttpHeader on for a specific connection of HttpClient?
[英]How to set HttpHeader on individual request using HttpClient
我有一个跨多个线程共享的HttpClient
:
public static class Connection
{
public static HttpClient Client { get; }
static Connection()
{
Client = new HttpClient
{
BaseAddress = new Uri(Config.APIUri)
};
Client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
Client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
它具有一些我放入每个请求的默认标头。 但是,当我使用它时,我只想为该请求添加标题:
var client = Connection.Client;
StringContent httpContent = new StringContent(myQueueItem, Encoding.UTF8, "application/json");
httpContent.Headers.Add("Authorization", "Bearer " + accessToken); // <-- Header for this and only this request
HttpResponseMessage response = await client.PostAsync("/api/devices/data", httpContent);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
当我这样做时,我得到一个例外:
{“滥用标头名称。请确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用。”
我找不到另一种向此请求添加请求标头的方法。 如果在Client
上修改DefaultRequestHeaders
,则会遇到线程问题,并且必须实施各种疯狂的锁定。
有任何想法吗?
您可以使用SendAsync发送HttpRequestMessage 。
例:
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, "/api/devices/data");
msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
msg.Content = new StringContent(myQueueItem, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(msg);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.