所有:
在将请求发送到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();
创建一个HttpRequestMessage,将Method设置为GET,设置标题,然后使用SendAsync代替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();