将 Http 标头添加到 HttpClient [英] Adding Http Headers to HttpClient
本文介绍了将 Http 标头添加到 HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在向 Web 服务发送请求之前,我需要将 http 标头添加到 HttpClient.我如何为单个请求执行此操作(而不是在 HttpClient 上针对所有未来请求)?我不确定这是否可能.
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.
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();
推荐答案
创建一个 HttpRequestMessage
,将 Method 设置为 GET
,设置您的标题,然后使用 SendAsync
而不是 GetAsync
.
Create a HttpRequestMessage
, set the Method to GET
, set your headers and then use SendAsync
instead of 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();
这篇关于将 Http 标头添加到 HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文