![](/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.