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 public HttpWebClient(IHttpClientFactory httpClientFactory)
6 {
7 this._httpClientFactory = httpClientFactory;
8 }
9 /// <summary>
10 /// Get请求
11 /// </summary>
12 /// <param name="url"></param>
13 /// <param name="dicHeaders"></param>
14 /// <param name="timeoutSecond"></param>
15 /// <returns></returns>
16 //public async Task<string> GetAsync(string url, int timeoutSecond = 120)
17 //{
18 // var client = _httpClientFactory.CreateClient();
19 // #region 最好不要这样绑定header,
20 // //DefaultRequestHeaders是和httpClient绑定的,当完成当前请求后,其它请求从factory中获取时,还是会有绑定的header的
21 // //会造成错误
22 // //if (dicHeaders != null)
23 // //{
24 // // foreach (var header in dicHeaders)
25 // // {
26 // // client.DefaultRequestHeaders.Add(header.Key, header.Value);
27 // // }
28 // //}
29 // #endregion
30 // client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
31 // var response = await client.GetAsync(url);
32 // var result = await response.Content.ReadAsStringAsync();
33 // return result;
34 //}
35
36
37
38
39 /// <summary>
40 /// Get异步请求
41 /// </summary>
42 /// <param name="url"></param>
43 /// <param name="dicHeaders"></param>
44 /// <param name="timeoutSecond"></param>
45 /// <returns></returns>
46 public async Task<string> GetAsync(string url, Dictionary<string, string> dicHeaders, int timeoutSecond = 120)
47 {
48 var client = _httpClientFactory.CreateClient();
49 var request = new HttpRequestMessage(HttpMethod.Get, url);
50 if (dicHeaders != null)
51 {
52 foreach (var header in dicHeaders)
53 {
54 request.Headers.Add(header.Key, header.Value);
55 }
56 }
57 client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
58 var response = await client.SendAsync(request);
59 if (response.IsSuccessStatusCode)
60 {
61 var result = await response.Content.ReadAsStringAsync();
62 return result;
63 }
64 else
65 {
66 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
67
68 }
69 }
70 /// <summary>
71 ///
72 /// </summary>
73 /// <param name="url"></param>
74 /// <param name="requestString"></param>
75 /// <param name="dicHeaders"></param>
76 /// <param name="timeoutSecond"></param>
77 /// <returns></returns>
78 public async Task<string> PostAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
79 {
80 var client = _httpClientFactory.CreateClient();
81 var requestContent = new StringContent(requestString);
82 if (dicHeaders != null)
83 {
84 foreach (var head in dicHeaders)
85 {
86 requestContent.Headers.Add(head.Key, head.Value);
87 }
88 }
89 client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
90 var response = await client.PostAsync(url, requestContent);
91 if (response.IsSuccessStatusCode)
92 {
93 var result = await response.Content.ReadAsStringAsync();
94 return result;
95 }
96 else
97 {
98 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
99 }
100 }
101 /// <summary>
102 ///
103 /// </summary>
104 /// <param name="url"></param>
105 /// <param name="requestString"></param>
106 /// <param name="dicHeaders"></param>
107 /// <param name="timeoutSecond"></param>
108 /// <returns></returns>
109 public async Task<string> PutAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
110 {
111 var client = _httpClientFactory.CreateClient();
112 var requestContent = new StringContent(requestString);
113 if (dicHeaders != null)
114 {
115 foreach (var head in dicHeaders)
116 {
117 requestContent.Headers.Add(head.Key, head.Value);
118 }
119 }
120 client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
121 var response = await client.PutAsync(url, requestContent);
122 if (response.IsSuccessStatusCode)
123 {
124 var result = await response.Content.ReadAsStringAsync();
125 return result;
126 }
127 else
128 {
129 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
130 }
131 }
132
133 /// <summary>
134 /// Patch异步请求
135 /// </summary>
136 /// <param name="url"></param>
137 /// <param name="requestString"></param>
138 /// <param name="dicHeaders"></param>
139 /// <param name="timeoutSecond"></param>
140 /// <returns></returns>
141 public async Task<string> PatchAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
142 {
143 var client = _httpClientFactory.CreateClient();
144 var requestContent = new StringContent(requestString);
145 if (dicHeaders != null)
146 {
147 foreach (var head in dicHeaders)
148 {
149 requestContent.Headers.Add(head.Key, head.Value);
150 }
151 }
152 client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
153 var response = await client.PatchAsync(url, requestContent);
154 if (response.IsSuccessStatusCode)
155 {
156 var result = await response.Content.ReadAsStringAsync();
157 return result;
158 }
159 else
160 {
161 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
162 }
163 }
164 public async Task<string> DeleteAsync(string url, Dictionary<string, string> dicHeaders, int timeoutSecond)
165 {
166 var client = _httpClientFactory.CreateClient();
167 var request = new HttpRequestMessage(HttpMethod.Delete, url);
168 if (dicHeaders != null)
169 {
170 foreach (var head in dicHeaders)
171 {
172 request.Headers.Add(head.Key, head.Value);
173 }
174 }
175 client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
176 var response = await client.SendAsync(request);
177 if (response.IsSuccessStatusCode)
178 {
179 var result = await response.Content.ReadAsStringAsync();
180 return result;
181 }
182 else
183 {
184 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
185 }
186 }
187 /// <summary>
188 /// 异步请求(通用)
189 /// </summary>
190 /// <param name="url"></param>
191 /// <param name="method"></param>
192 /// <param name="requestString"></param>
193 /// <param name="dicHeaders"></param>
194 /// <param name="timeoutSecond"></param>
195 /// <returns></returns>
196 public async Task<string> ExecuteAsync(string url, HttpMethod method, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond = 120)
197 {
198 var client = _httpClientFactory.CreateClient();
199 var request = new HttpRequestMessage(method, url)
200 {
201 Content = new StringContent(requestString),
202 };
203 if (dicHeaders != null)
204 {
205 foreach (var header in dicHeaders)
206 {
207 request.Headers.Add(header.Key, header.Value);
208 }
209 }
210 var response = await client.SendAsync(request);
211 if (response.IsSuccessStatusCode)
212 {
213 var result = await response.Content.ReadAsStringAsync();
214 return result;
215 }
216 else
217 {
218 throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
219 }
220 }
221
222 }
CustomerHttpException类的简单定义
    public class CustomerHttpException : Exception
{
public CustomerHttpException() : base()
{ }
public CustomerHttpException(string message) : base(message)
{ }
}

.NetCore简单封装基于IHttpClientFactory的HttpClient请求的更多相关文章

  1. iOS sqlite 增删改查 简单封装(基于 FMDB)

    /** *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * *  基于 FMDB * *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...

  2. react封装基于axios的API请求

    一.最近做的一个后台管理项目,基于antd-pro做的,需要封装基于axios请求,便于开发,直接上代码. import axios from 'axios'; export const Method ...

  3. Jquery Ajax简单封装(集中错误、请求loading处理)

    Jquery Ajax简单封装(集中错误.请求loading处理) 对Jquery Ajax做了简单封装,错误处理,请求loading等,运用到项目中集中处理会很方便. 技术层面没有什么好说的,请求是 ...

  4. 简单的基于Vue-axios请求封装

    具体实现思路=>封装之前需要用npm安装并引入axios,使用一个单独的js模块作为接口请输出对象,然后export dafult 这个对象. 1.首先我们需要在Vue实例的原型prototyp ...

  5. Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求

    HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...

  6. NetCore控制台程序-使用HostService和HttpClient实现简单的定时爬虫

    .NetCore承载系统 .NetCore的承载系统, 可以将长时间运行的服务承载于托管进程中, AspNetCore应用其实就是一个长时间运行的服务, 启动AspNetCore应用后, 它就会监听网 ...

  7. python网页请求urllib2模块简单封装代码

    这篇文章主要分享一个python网页请求模块urllib2模块的简单封装代码. 原文转自:http://www.jbxue.com/article/16585.html 对python网页请求模块ur ...

  8. 最简单的基于FFMPEG的封装格式转换器(无编解码)

    本文介绍一个基于FFMPEG的封装格式转换器.所谓的封装格式转换,就是在AVI,FLV,MKV,MP4这些格式之间转换(相应.avi,.flv,.mkv,.mp4文件).须要注意的是,本程序并不进行视 ...

  9. 最简单的基于FFmpeg的封装格式处理:视音频复用器(muxer)

    ===================================================== 最简单的基于FFmpeg的封装格式处理系列文章列表: 最简单的基于FFmpeg的封装格式处理 ...

随机推荐

  1. Nuget管理自己的项目库

    Nuget是什么 Nuget 是一种 Visual Studio 扩展工具,它能够简化在 Visual Studio 项目中添加.更新和删除库(部署为程序包)的操作.(官方地址)相信大家对这个应该还是 ...

  2. Communicating to 2 SPI Slaves with USART & SPI ports on Atmega16U2

    原文来自:https://www.avrfreaks.net/comment/2236256 I'm writing code for an embedded chip that consists o ...

  3. 【学习笔记】Polya定理

    笔者经多番周折终于看懂了\(\text{Burnside}\)定理和\(\text{Polya}\)定理,特来写一篇学习笔记来记录一下. 群定义 定义:群\((G,·)\)是一个集合与一个运算·所定义 ...

  4. HTML CSS+JS想要做放大镜练习,如何获取同样的大图和小图?

    1.进入某商城找到对应的图片: 步骤一: 步骤二: 步骤三: 2.检查源代码: 情况一:按F12 情况二:鼠标在网页内,直接右键-->"检查元素" 1.选中选择部分 2.点击 ...

  5. 秒懂JVM的垃圾回收机制

    前言 阅读过王子之前JVM文章的小伙伴们,应该已经对JVM的内存分布情况有了一个清晰的认识了,今天我们就接着来聊聊JVM的垃圾回收机制,让小伙伴们轻松理解JVM是怎么进行垃圾回收的. 复制算法.Ede ...

  6. hashCode()方法源码分析

    执行代码 public class Demo06 { public static void main(String[] args) { String s="hello"; Syst ...

  7. MeteoInfoLab脚本示例:FY-3C全球火点HDF数据

    FY-3C全球火点HDF数据包含一个FIRES二维变量,第一维是火点数,第二维是一些属性,其中第3.4列分别是火点的纬度和经度.下面的脚本示例读出所有火点经纬度并绘图.脚本程序: #Add data ...

  8. 【纯水题】POJ 1852 Ants

    题目大意 有一根长\(L\)厘米米的水平木棍上有\(n\)个蚂蚁,它们以每秒1cm/s的爬(fei)行(ben)到木棍的一端,之后掉下去. 给出每个蚂蚁的起始位置,但是不知道它们爬行的方向.相向而行的 ...

  9. goland 注册

    注意:本教程已过期  请使用其他人教程激活最新版   https://www.789zhao.com/blog/JC08EIFBS9TM.html https://shimo.im/docs/dKYC ...

  10. centos8平台使用iostat监控磁盘io

    一,iostat所属的包: [root@centos8 ~]# whereis iostat iostat: /usr/bin/iostat /usr/share/man/man1/iostat.1. ...