C#网络请求封装,HttpClient 静态单实例

2024-08-23 05:36

本文主要是介绍C#网络请求封装,HttpClient 静态单实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于为什么使用单实例,请参考: HttpClient的错误使用

每次使用网络请求时都实例一个HttpClient,业务量小的时候不会存在问题,但是当请求足够大时,按照相关测试 短时间内(两分钟)当请求在3000-5000时请求响应将会下降 会存在大量的网络等待,当超过5000时会请求错误,显示socket连接耗尽,HttpClient默认释放时间是2-3分钟来着

该请求封装了基本的 异步post、get请求,文件的上传、下载。响应体压缩解码功能

完整代码

public static class HttpRequestHelper
{// 关于调整的原因,可查看:https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/// 这里将请求设置为全局的单例,这是安全的 因为HttpClient底层是线程安全的// 设置默认的超时时间,因为是单例 所以不能在执行中修改基础的实例信息private static readonly HttpClient _client = new HttpClient() { Timeout = TimeSpan.FromSeconds(120) };/// <summary>/// 发送异步post请求/// </summary>/// <param name="baseUrl"></param>/// <param name="headers">请不要在请求头中添加 Content-Type</param>/// <param name="data"></param>/// <param name="contentType"></param>/// <param name="parameters">Parameter 参数</param>/// <returns></returns>/// <exception cref="ArgumentException"></exception>public static async Task<string> HttpPostAsync(string baseUrl, Dictionary<string, string>? headers = null, object? data = null, ContentType contentType = ContentType.Json, Dictionary<string, string>? parameters = null){// 将参数添加到 URL 中var url = BuildUrl(baseUrl, parameters);using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);if (headers != null){foreach (var header in headers){request.Headers.Add(header.Key, header.Value);}}if (data != null)request.Content = BuildContent(data, contentType);HttpResponseMessage response = await _client.SendAsync(request);string responseBody = await DeCodeResponse(response);EnsureSuccessStatus(response, responseBody, "Post请求", url, headers?.ToJson(), data?.ToJson());return responseBody;}/// <summary>/// 发送异步GET请求/// </summary>/// <param name="baseUrl"></param>/// <param name="parameters"></param>/// /// <param name="headers">请不要在请求头中添加 Content-Type</param>/// <returns></returns>public static async Task<string> HttpGetAsync(string baseUrl, Dictionary<string, string>? parameters = null, Dictionary<string, string>? headers = null, object? data = null,ContentType contentType = ContentType.Json){var url = BuildUrl(baseUrl, parameters);using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);if (headers != null){foreach (var header in headers){request.Headers.Add(header.Key, header.Value);}}if (data != null)request.Content = BuildContent(data, contentType);var response = await _client.SendAsync(request);var content = await DeCodeResponse(response);EnsureSuccessStatus(response, content, "Get请求", url, headers?.ToJson(), data?.ToJson());return content;}/// <summary>/// 异步上传文件/// </summary>/// <param name="baseUrl">上传地址</param>/// <param name="filePath">文件地址</param>/// <param name="headers">请求头</param>/// <param name="parameters">query参数</param>/// <returns></returns>public static async Task<string> UploadFileAsync(string baseUrl, string filePath, Dictionary<string, string>? headers = null,Dictionary<string, string>? parameters = null){// 将参数添加到 URL 中var url = BuildUrl(baseUrl, parameters);using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);if (headers != null){foreach (var header in headers){request.Headers.Add(header.Key, header.Value);}}// 构建多媒体请求内容var content = new MultipartFormDataContent();// 普通文件上传var fileContent = new StreamContent(File.OpenRead(filePath));content.Add(fileContent, "file", Path.GetFileName(filePath));// 读取文件内容并压缩.发现两个问题。如有需要再做压缩// 1、发现压缩上传会导致进程内存占用非常大 短期内无法释放// 2、压缩上传的文件 无法正常打开。可能是接收方没有解压缩导致//string fileContent = File.ReadAllText(filePath);//byte[] compressedData = CompressString(fileContent);//var compressedContent = new ByteArrayContent(compressedData);//content.Add(compressedContent, "file", Path.GetFileName(filePath));request.Content = content;// 发送 POST 请求var response = await _client.SendAsync(request);//response.EnsureSuccessStatusCode();string responseBody = await DeCodeResponse(response);EnsureSuccessStatus(response, responseBody, "文件上传", url, headers?.ToJson());return responseBody;}/// <summary>/// 异步下载文件/// </summary>/// <param name="url"></param>/// <param name="savePath"></param>/// <param name="method"></param>/// <param name="headers"></param>/// <param name="data"></param>/// <param name="contentType"></param>/// <returns></returns>/// <exception cref="Exception"></exception>public static async Task DownloadFileAsync(string url, string savePath, HttpMethod method,Dictionary<string, object>? headers = null, object? data = null, ContentType contentType = ContentType.Json){using HttpRequestMessage request = new HttpRequestMessage(method, url);if (headers != null){foreach (var header in headers){request.Headers.Add(header.Key, header.Value.ToString());}}if (data != null)request.Content = BuildContent(data, contentType);using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);EnsureSuccessStatus(response, "", "文件下载", url, headers?.ToJson(), data?.ToJson());// 获取文件总长度(可选,用于显示进度或检查文件大小)var totalBytes = response.Content.Headers.ContentLength;using var streamToReadFrom = await response.Content.ReadAsStreamAsync();using var streamToWriteTo = File.Create(savePath);await streamToReadFrom.CopyToAsync(streamToWriteTo);}/// <summary>/// 验证请求状态/// </summary>/// <param name="response"></param>/// <param name="responseBody"></param>/// <param name="method"></param>/// <exception cref="Exception"></exception>private static void EnsureSuccessStatus(HttpResponseMessage response, string responseBody, string method, string url, string? header, string? body = null){//response.EnsureSuccessStatusCode(); 检查响应是否是200 若不是 引发异常// 401 404 状态 应该交给上层业务处理if (!response.IsSuccessStatusCode&& ((int)response.StatusCode != 401 && (int)response.StatusCode != 404)){Exception exception = new Exception($"header:{header};body:{body};res:{responseBody}");throw new HttpRequestVerifyException($"{method} {url} ({(int)response.StatusCode}){response.StatusCode}", exception);}}/// <summary>/// 解码响应体,如果有编码或压缩的话/// </summary>/// <param name="response"></param>/// <returns></returns>private static async Task<string> DeCodeResponse(HttpResponseMessage response){// 解码信息if (response.Content.Headers != null && response.Content.Headers.ContentEncoding.Contains("gzip")){// 解码using var gzipStream = new GZipStream(await response.Content.ReadAsStreamAsync(), CompressionMode.Decompress);using var streamReader = new StreamReader(gzipStream, Encoding.UTF8);return await streamReader.ReadToEndAsync();}elsereturn await response.Content.ReadAsStringAsync();}/// <summary>/// 将请求数据绑定到url/// </summary>/// <param name="baseUrl"></param>/// <param name="parameters"></param>/// <returns></returns>private static string BuildUrl(string baseUrl, Dictionary<string, string>? parameters){if (parameters == null || parameters.Count == 0)return baseUrl;var queryStrings = new List<string>();foreach (var parameter in parameters){var encodedKey = Uri.EscapeDataString(parameter.Key);var encodedValue = Uri.EscapeDataString(parameter.Value);queryStrings.Add($"{encodedKey}={encodedValue}");}var queryString = string.Join("&", queryStrings);return $"{baseUrl}?{queryString}";}/// <summary>/// 绑定数据到请求体中/// </summary>/// <param name="data"></param>/// <param name="contentType"></param>/// <returns></returns>/// <exception cref="ArgumentException"></exception>private static HttpContent BuildContent(object data, ContentType contentType){HttpContent content;if (contentType == ContentType.FormUrlEncoded){var formData = new FormUrlEncodedContent(ObjectToKeyValue(data));content = formData;}else if (contentType == ContentType.Json){//var jsonData = JsonConvert.SerializeObject(data, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" });content = new StringContent(data.ToString() ?? "", Encoding.UTF8, "application/json");}else if (contentType == ContentType.Xml){content = new StringContent(data.ToString() ?? "", Encoding.UTF8, "text/xml");}else if (contentType == ContentType.MultipartFormData){if (data is IDictionary<string, object> formDataDict){var formContent = new MultipartFormDataContent();foreach (var kvp in formDataDict){var value = kvp.Value?.ToString() ?? "";formContent.Add(new StringContent(value), kvp.Key);}content = formContent;}else{throw new ArgumentException("formData must be a Dictionary<string, object>.");}}else{throw new ArgumentException("Invalid contentType. Supported values are 'application/x-www-form-urlencoded','application/json','text/xml','multipart/form-data'.");}return content;}/// <summary>/// 压缩文件 返回压缩后的byte/// </summary>/// <param name="input"></param>/// <returns></returns>private static byte[] CompressString(string input){using MemoryStream output = new MemoryStream();using (GZipStream gzipStream = new GZipStream(output, CompressionMode.Compress, leaveOpen: true))using (StreamWriter writer = new StreamWriter(gzipStream)){writer.Write(input);}return output.ToArray();}private static IEnumerable<KeyValuePair<string, string>> ObjectToKeyValue(object obj){var properties = obj.GetType().GetProperties();foreach (var prop in properties){var value = prop.GetValue(obj)?.ToString() ?? string.Empty;yield return new KeyValuePair<string, string>(prop.Name, value);}}
}public enum ContentType
{Json,FormUrlEncoded, // application/x-www-form-urlencodedMultipartFormData,Xml
}

这篇关于C#网络请求封装,HttpClient 静态单实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1098498

相关文章

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

C#比较两个List集合内容是否相同的几种方法

《C#比较两个List集合内容是否相同的几种方法》本文详细介绍了在C#中比较两个List集合内容是否相同的方法,包括非自定义类和自定义类的元素比较,对于非自定义类,可以使用SequenceEqual、... 目录 一、非自定义类的元素比较1. 使用 SequenceEqual 方法(顺序和内容都相等)2.

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

Go语言利用泛型封装常见的Map操作

《Go语言利用泛型封装常见的Map操作》Go语言在1.18版本中引入了泛型,这是Go语言发展的一个重要里程碑,它极大地增强了语言的表达能力和灵活性,本文将通过泛型实现封装常见的Map操作,感... 目录什么是泛型泛型解决了什么问题Go泛型基于泛型的常见Map操作代码合集总结什么是泛型泛型是一种编程范式,允

C#从XmlDocument提取完整字符串的方法

《C#从XmlDocument提取完整字符串的方法》文章介绍了两种生成格式化XML字符串的方法,方法一使用`XmlDocument`的`OuterXml`属性,但输出的XML字符串不带格式,可读性差,... 方法1:通过XMLDocument的OuterXml属性,见XmlDocument类该方法获得的xm

C#多线程编程中导致死锁的常见陷阱和避免方法

《C#多线程编程中导致死锁的常见陷阱和避免方法》在C#多线程编程中,死锁(Deadlock)是一种常见的、令人头疼的错误,死锁通常发生在多个线程试图获取多个资源的锁时,导致相互等待对方释放资源,最终形... 目录引言1. 什么是死锁?死锁的典型条件:2. 导致死锁的常见原因2.1 锁的顺序问题错误示例:不同

mysqld_multi在Linux服务器上运行多个MySQL实例

《mysqld_multi在Linux服务器上运行多个MySQL实例》在Linux系统上使用mysqld_multi来启动和管理多个MySQL实例是一种常见的做法,这种方式允许你在同一台机器上运行多个... 目录1. 安装mysql2. 配置文件示例配置文件3. 创建数据目录4. 启动和管理实例启动所有实例

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

解读静态资源访问static-locations和static-path-pattern

《解读静态资源访问static-locations和static-path-pattern》本文主要介绍了SpringBoot中静态资源的配置和访问方式,包括静态资源的默认前缀、默认地址、目录结构、访... 目录静态资源访问static-locations和static-path-pattern静态资源配置