HttpClient 调用 RestAPI 接口的用法
Dotnet 源代码 github地址:https://github.com/dotnet/core/tree/v5.0.0
HttpClient 是否Dotnet 客户端调用 RestAPI 接口的类,开源的还有 RestSharp (https://restsharp.dev),
HttpClient 的官方使用文档:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0
网文参考: "优雅通过HttpClientFactory使用HttpClient" 。
“Create HTTPClient using IHttpClientFactory in ASP.NET Core”
网上有一篇介绍使用的文章: 揭秘通用平台的 HttpClient (译), 调用逻辑图示:
全部来自: 几个主要类(在 System.Net.Http 空间中):
HttpClient : 继承于 HttpMessageInvoker (重点是:构造器 HttpMessageInvoker(HttpMessageHandler, [Boolean]),与方法 Send[Async](HttpRequestMessage, CancellationToken))
属性:BaseAddress、 Timeout、MaxResponseContentBufferSize(long整数)、
DefaultRequestHeaders、DefaultRequestVersion、DefaultVersionPolicy、DefaultProxy 几个默认属性值
方法: CancelPendingRequests()、下列方法全部依赖: SendAsync (HttpRequestMessage, CancellationToken)
DeleteAsync(String/Uri, CancellationToken)、
PatchAsync(String/Uri, HttpContent, CancellationToken)、
PostAsync((String/Uri, HttpContent, CancellationToken)、
PutAsync(String/Uri, HttpContent, CancellationToken)、下列四个同类 Get 。
GetAsync(String/Uri, HttpCompletionOption, CancellationToken)、GetByteArrayAsync(String/Uri, CancellationToken)、
GetStringAsync(String/Uri, CancellationToken)、GetStreamAsync(String/Uri, CancellationToken)
扩展:GetFromJsonAsync(HttpClient, String/Uri, Type, JsonSerializerOptions, CancellationToken),
GetFromJsonAsync<TValue>(HttpClient, String/Uri, JsonSerializerOptions, CancellationToken),
PostAsJsonAsync<TValue>(HttpClient, String/Uri, TValue, JsonSerializerOptions, CancellationToken)
PutAsJsonAsync<TValue>(HttpClient, String/Uri, TValue, JsonSerializerOptions, CancellationToken)
HttpClientHandler : 继承于 HttpMessageHandler(抽象) , 派生了:WebRequestHandler
(此文:将HttpClientHandler传递给HttpClient时调用哪个SendAsync方法 ---- 解释了调用顺序。)
(另一E文 HttpClient, HttpClientHandler, and WebRequestHandler Explained 解释 ---- 介绍三者 )
(参考:How to use HttpClientHandler with IHttpClientFactory ? )
方法:继承 HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken); ===
继承 Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
属性: