起因 :由于需要前段时间写了一个http请求的公共方法 使用的 HttpClient,但是在jmeter测试下 爆发了这个问题:“Cannot assign requested address Cannot assign requested address”;百度了一翻,基本都是说的端口占用完,也有很多解决方案,其中就找到了IHttpClientFactory这个解决方案,同时也抛弃之前的HttpClient用法,至于HttpClient和IHttpClientFactory的区别就不在记录了,网上很多,最大区别就是IHttpClientFactory解决释放问题开发不需要关心到的问题,用这个组件的原因也是因为目前项目也是使用的.net core ,就刚好集成进去。
但是在查询IHttpClientFactory使用时,遇到些问题,查询时,发现基本都是在官网复制下来的,但是我复制下来也用不了,因为基础差也是百度了很久终于理出来了,在此记录下来,如有大神路过还望指点一下,代码可以直接复制使用,调用时注入服务即可
/// <summary> /// http 请求服务 /// </summary> public interface IHttpClientHelper: IApplicationService { /// <summary> /// 使用post返回异步请求直接返回对象 /// </summary> /// <typeparam name="T">返回对象类型</typeparam> /// <typeparam name="T2">请求对象类型</typeparam> /// <param name="url">请求链接</param> /// <param name="obj">请求对象数据</param> /// <param name="header">请求头</param> /// <param name="postFrom">表单提交 注* postFrom不为null 代表表单提交, 为null标识惊悚格式请求</param> /// <param name="gzip">是否压缩</param> /// <returns>请求返回的目标对象</returns> Task<T> PostObjectAsync<T, T2>(string url, T2 obj, Dictionary<string, string> header = null, Dictionary<string, string> postFrom = null, bool gzip = false); /// <summary> /// 使用Get返回异步请求直接返回对象 /// </summary> /// <typeparam name="T">请求对象类型</typeparam> /// <param name="url">请求链接</param> /// <returns>返回请求的对象</returns> Task<T> GetObjectAsync<T>(string url); }
/// <summary> /// http 请求服务 /// </summary> public class HttpClientHelper : ApplicationService, IHttpClientHelper { private readonly IHttpClientFactory _httpClientFactory; /// <summary> /// 构造函数 /// </summary> /// <param name="httpClientFactory"></param> public HttpClientHelper(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } #region http 请求方式 /// <summary> /// 使用post方法异步请求 /// </summary> /// <param name="url">目标链接</param> /// <param name="posData">发送的参数JSON字符串</param> /// <param name="header">请求头</param> /// <param name="posFrom">表单提交格式</param> /// <param name="gzip">是否压缩</param> /// <returns>返回的字符串</returns> public async Task<string> PostAsync(string url, string posData, Dictionary<string, string> header = null, Dictionary<string, string> posFrom = null,bool gzip = false) { //从工厂获取请求对象 var client = _httpClientFactory.CreateClient(); //消息状态 string responseBody = string.Empty; //存在则是表单提交信息 if (posFrom != null) { var formData = new MultipartFormDataContent(); foreach (var item in posFrom) { formData.Add(new StringContent(item.Value), item.Key); } //提交信息 var result = await client.PostAsync(url, formData); //获取消息状态 responseBody = await result.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); } else {//json HttpContent content = new StringContent(posData); if (header != null) { client.DefaultRequestHeaders.Clear(); foreach (var item in header) { client.DefaultRequestHeaders.Add(item.Key, item.Value); } } content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); if (gzip) { GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync()); responseBody = new StreamReader(inputStream).ReadToEnd(); } else { responseBody = await response.Content.ReadAsStringAsync(); } } return responseBody; } /// <summary> /// 使用get方法异步请求 /// </summary> /// <param name="url">目标链接</param> /// <param name="header"></param> /// <param name="Gzip"></param> /// <returns>返回的字符串</returns> public async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false) { var client = _httpClientFactory.CreateClient(); //HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); if (header != null) { client.DefaultRequestHeaders.Clear(); foreach (var item in header) { client.DefaultRequestHeaders.Add(item.Key, item.Value); } } HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode();//用来抛异常 string responseBody = ""; if (Gzip) { GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync()); responseBody = new StreamReader(inputStream).ReadToEnd(); } else { responseBody = await response.Content.ReadAsStringAsync(); } return responseBody; } /// <summary> /// 使用post返回异步请求直接返回对象 /// </summary> /// <typeparam name="T">返回对象类型</typeparam> /// <typeparam name="T2">请求对象类型</typeparam> /// <param name="url">请求链接</param> /// <param name="obj">请求对象数据</param> /// <param name="header">请求头</param> /// <param name="postFrom">表单提交 表单提交 注* postFrom不为null 代表表单提交, 为null标识惊悚格式请求</param> /// <param name="gzip">是否压缩</param> /// <returns>请求返回的目标对象</returns> public async Task<T> PostObjectAsync<T, T2>(string url, T2 obj,Dictionary<string, string> header = null, Dictionary<string, string> postFrom = null, bool gzip = false) { String json = JsonConvert.SerializeObject(obj); string responseBody = await PostAsync(url, json, header, postFrom, gzip); //请求当前账户的信息 return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化 } /// <summary> /// 使用Get返回异步请求直接返回对象 /// </summary> /// <typeparam name="T">请求对象类型</typeparam> /// <param name="url">请求链接</param> /// <returns>返回请求的对象</returns> public async Task<T> GetObjectAsync<T>(string url) { string responseBody = await GetAsync(url); //请求当前账户的信息 return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化 } #endregion }
注* 我这里项目版本是.net core 2.2 在添加 IHttpClientFactory nueget包时根据自身版本号添加 大于.net 2.2 的可忽略 此外:
1.使用前需要在 Startup.cs 类 注入
//默认生命周期为2分钟,可以使用此方法+配置 修改默认时间 SetHandlerLifetime(TimeSpan.FromMinutes(X));
services.AddHttpClient(); 具体介绍到官网查阅,