首页 文章

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

提问于
浏览
4

我有一个跨多个线程共享的 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"));
    }
}

它有一些我放在每个请求上的默认标头 . 但是,当我使用它时,我想为该请求添加 Headers :

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

当我这样做时,我得到了例外:

{“Misused header name . 确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用 . ”}

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

有任何想法吗?

1 回答

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

相关问题