簡體   English   中英

如何使用HttpClient對單個請求設置HttpHeader

[英]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

在消息中,您可以設置uri方法內容標題

例:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM