.NetCore简单封装基于IHttpClientFactory的HttpClient请求
.NetCore简单封装基于IHttpClientFactory的HttpClient请求
IHttpClientFactory是什么?为什么出现了IHttpClientFactory
一、IHttpClientFactory是什么?
IHttpClientFactory是.netcore2.1才开始引入的,是HttpClient的工厂接口,它为我们提供了获取HttpClient的接口,它帮助我们维护HttpClient的生命周期。当我们需要HttpClient访问网络时,它会自动帮我们获取或者是创建HttpClient(存在空闲的HttpClient时,直接提供;当不存在可用的HttpClient时自动创建)。它相当于HttpClient池。
二、为什么出现IHttpClientFactory?
传统的HttpClient创建后,其占用了Socket资源并且其不会是及时的回收。我们每次new一个HttpClient时是一个全新的对象,所以在高并发下又是会导致socket资源耗尽(Unable to connect to the remote serverSystem.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.)。而如果采用单例或者静态的HttpClient,却达不到高效的使用网络请求,而且当访问不同的url时,单例或者静态的HttpClient往往会导致访问混乱而出现错误。
.NetCore简单封装基于IHttpClientFactory的HttpClient请求
1 public class HttpWebClient
2 {
3
4 private IHttpClientFactory _httpClientFactory;
5 private readonly ILogger _logger;
6 public HttpWebClient(IHttpClientFactory httpClientFactory, ILogger logger)
7 {
8 this._httpClientFactory = httpClientFactory;
9 this._logger = logger;
10 }
11
12 ///
13 /// Get
14 ///
15 ///
16 ///
17 ///
18 ///
19 public async Task GetAsync(string url, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
20 {
21 try
22 {
23 var client = BuildHttpClient(dicHeaders, timeoutSecond);
24 var response = await client.GetAsync(url);
25 var responseContent = await response.Content.ReadAsStringAsync();
26 if (response.IsSuccessStatusCode)
27 {
28 return JsonUtil.Deserialize(responseContent);
29 }
30 else
31 {
32 throw new CustomerHttpException(response.StatusCode.ToString(), responseContent);
33 }
34 }
35 catch (Exception ex)
36 {
37 _logger.LogError($"HttpGet:{url} Error:{ex.ToString()}");
38 throw new Exception($"HttpGet:{url} Error", ex);
39 }
40 }
41 ///
42 /// Post
43 ///
44 ///
45 ///
46 ///
47 ///
48 ///
49 public async Task PostAsync(string url, string requestBody, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
50 {
51 try
52 {
53 var client = BuildHttpClient(null, timeoutSecond);
54 var requestContent = GenerateStringContent(requestBody, dicHeaders);
55 var response = await client.PostAsync(url, requestContent);
56 var responseContent = await response.Content.ReadAsStringAsync();
57 if (response.IsSuccessStatusCode)
58 {
59 var result = JsonUtil.Deserialize(responseContent);
60 return result;
61 }
62 else
63 {
64 throw new CustomerHttpException(response.StatusCode.ToString(), responseContent);
65 }
66 }
67 catch (Exception ex)
68 {
69 _logger.LogError($"HttpPost:{url},body:{requestBody} Error:{ex.ToString()}");
70 throw new Exception($"HttpPost:{url} Error", ex);
71 }
72 }
73 ///
74 /// Put
75 ///
76 ///
77 ///
78 ///
79 ///
80 ///
81 public async Task PutAsync(string url, string requestBody, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
82 {
83