HttpClient
的所有方法,即GetAsync
,PostAsync
等内部是否都在调用SendAsync
方法?
答案 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/");
...
}