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

时间:2017-02-15 16:39:12

标签: c# .net http-headers webclient

我有一个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对象的内容标题。“}

我找不到另一种方法来向此请求添加请求标头。如果我修改DefaultRequestHeaders上的Client,我会遇到线程问题,并且必须实现各种疯狂锁定。

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

您可以使用SendAsync发送HttpRequestMessage

在邮件中,您可以设置urimethodcontentheaders

示例:

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();