如何使用HttpClient在单个请求上设置HttpHeader

我有一个跨多个线程共享的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();
链接地址: http://www.djcxy.com/p/46257.html

上一篇: How to set HttpHeader on individual request using HttpClient

下一篇: Cannot set Headers on HttpFormUrlEncodedContent