3

HttpClientieGetAsync等的所有方法都在PostAsync内部调用SendAsync方法吗?

4

1 回答 1

4

是的,它HttpClient使用HttpMessageHandler底层来执行所有 HTTP 请求。该HttpMessageHandler方法Task<HttpResponseMessage> SendAsync(HttpRequestMessage, CancellationToken)是由HttpClient.

抽象类的默认实现HttpMessageHandlerHttpClientHandler.

您可以将自己的HttpMessageHandler实现传递给HttpClient接受一个的构造函数。尽管您不太可能需要,但有一些应用程序。例如,如果您想记录您HttpClient提出的每个请求。你可以LoggingHttpMessageHandlerHttpMessageHandler.

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/");
    ...
}
于 2015-10-30T14:53:41.203 回答