C# 将 Http 标头添加到 HttpClient
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12022965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Http Headers to HttpClient
提问by Ryan Pfister
All:
全部:
I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible.
在向 Web 服务发送请求之前,我需要将 http 标头添加到 HttpClient。我如何为单个请求执行此操作(而不是在 HttpClient 上针对所有未来请求)?我不确定这是否可能。
var client = new HttpClient();
var task =
client.GetAsync("http://www.someURI.com")
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
采纳答案by Darrel Miller
Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsyncinstead of GetAsync.
创建一个HttpRequestMessage,将方法设置为GET,设置标题,然后使用SendAsync而不是GetAsync。
var client = new HttpClient();
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
回答by Taran
When it can be the same header for all requests oryou dispose the client after each request you can use the DefaultRequestHeaders.Addoption:
当它可以是所有请求的相同标头时,或者您在每个请求之后处理客户端时,您可以使用该DefaultRequestHeaders.Add选项:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");
回答by Zimba
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:
要根据请求设置自定义标头,请使用自定义标头构建请求,然后再将其传递给 httpclient 以发送到 http 服务器。例如:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
默认标头是 SET ON HTTPCLIENT 发送到服务器的每个请求。

