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. Solon详解(十)- 怎么用 Solon 开发基于 undertow jsp tld 的项目?

    Solon详解系列文章: Solon详解(一)- 快速入门 Solon详解(二)- Solon的核心 Solon详解(三)- Solon的web开发 Solon详解(四)- Solon的事务传播机制 ...

  2. selenium-自动化测试51job网站(MacOS + Safari)2020年10月6日

    登录 51job ,http://www.51job.com 输入搜索关键词 "python", 地区选择 "杭州"(注意,如果所在地已经选中其他地区,要去掉) ...

  3. Python导入模块的几种方法

    Python 模块 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python 代 ...

  4. c++中 预编译头文件PCH

    转载:https://blog.csdn.net/lovemysea/article/details/74858430 一.预编译头文件使用经验: 如果预编译头文件被正确使用时,它确实大大提高我们编程 ...

  5. 【题解】[CQOI]动态逆序对

    题目链接 题意如题,维护一个动态序列的逆序对总数. 注意题目给的是\([1,n]\)的排列,所以没必要离散化了. 考虑逆序对:二维偏序可以用树状数组做,现在是三维偏序,即加了一个时间维度. 找一个数前 ...

  6. Systemd的权威用法【译】

    如何使用journalctl 来观察和操作systemd的日志 介绍 systemd的一些不错的有点就是它能涉及到进程的系统的日志.对于其他日志工具,日志通常被分布到整个系统中,由不同的daemon和 ...

  7. MySQL 之 innodb 日志管理 -- 1. 基本日志文件

    1.基本日志文件分类 错误日志(error log) 慢查询日志日志(slow query log) 二进制日志(binlog) 查询日志(general log) 2.错误日志 主要包括mysql的 ...

  8. C#与sql进行图片存取

    1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Da ...

  9. 【C语言C++编程入门】程序的可读性和函数的调用!

    一个简单程序的结构 你已经看过一个具体的例子,下面可以了解一些 C程序的基本规则了. 程序由一个或多个函数组成,其中一定有一个名为 main()的函数.函数的描述由函数头和函数体组成.函数头包括预处理 ...

  10. Linux发行版教你如何选 给入门者的选择通法

    Linux的发行版何止琳琅满目,简直是乱入你眼. 本篇将介绍选择发行版的经验和通用法则,主要会从PC角度去谈. 更新于2020年,初次发布于2017年 选择发行版需考虑哪些因素 选择发行版时需要考虑的 ...