HttpClient的所有方法都在内部调用SendAsync方法吗?

时间:2015-10-30 11:00:18

标签: asp.net asp.net-web-api httpclient sendasync getasync

HttpClient的所有方法,即GetAsyncPostAsync等内部是否都在调用SendAsync方法?

1 个答案:

答案 0 :(得分:3)

是的,HttpClient使用下面的HttpMessageHandler来执行所有HTTP请求。 HttpMessageHandler方法Task<HttpResponseMessage> SendAsync(HttpRequestMessage, CancellationToken)HttpClient调用的方法。

抽象类HttpMessageHandler的默认实现是HttpClientHandler

You can pass in your own HttpMessageHandler implementation to the HttpClient constructor that takes one.虽然您不太可能需要,但有应用程序。例如,如果您想记录HttpClient生成的每个请求。您可以为LoggingHttpMessageHandler制作HttpMessageHandler装饰器。

using (var handler = new HttpClientHandler())
using (var loggingHandler = new LoggingHttpClientHandler(handler, logger))
using (var client = new HttpClient(loggingHandler))
{
    // Logs "GET https://www.google.com/"
    var response = await client.GetAsync("https://www.google.com/");
    ...
}