小编典典

将 Http 标头添加到 HttpClient

all

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

阅读 85

收藏
2022-07-18

共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();
2022-07-18