小编典典

将Http标头添加到HttpClient

c#

所有:

在将请求发送到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();

阅读 248

收藏
2020-05-19

共1个答案

小编典典

创建一个HttpRequestMessage,将Method设置为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();
2020-05-19