如何使用HttpClient对单个请求设置HttpHeader [英] How to set HttpHeader on individual request using HttpClient

查看:859
本文介绍了如何使用HttpClient对单个请求设置HttpHeader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HttpClient可以在多个线程之间共享:

I have an HttpClient that is shared across multiple threads:

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"));
    }
}

我在每个请求中都添加了一些默认标头.但是,当我使用它时,我想为请求的 just 添加标题:

It has some default headers I put onto each request. However, when I use it, I want to add on a header for just that request:

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

执行此操作时,出现异常:

When I do this, I get the exception:

{标头名称滥用.请确保请求标头与 HttpRequestMessage,带有HttpResponseMessage的响应标头和 带有HttpContent对象的内容标题.}

{"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}

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

I couldn't find another way to add request headers to this request. If I modify the DefaultRequestHeaders on Client, I run into thread issues and would have to implement all sorts of crazy locking.

有什么想法吗?

推荐答案

您可以使用在消息中,您可以设置 uri

In the message you can setup the uri, method, content and headers.

示例:

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

这篇关于如何使用HttpClient对单个请求设置HttpHeader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆