news 2026/6/18 11:21:57

C#实现的全能HTTP POST工具类

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C#实现的全能HTTP POST工具类

C#实现的全能HTTP POST工具类,整合了多种协议格式、安全认证和扩展能力,支持JSON、表单、文件上传等场景:


一、核心工具类实现

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Net;usingSystem.Net.Http;usingSystem.Text;usingSystem.Threading.Tasks;usingNewtonsoft.Json;publicclassHttpPostHelper{privatereadonlyHttpClient_httpClient;privatereadonlyDictionary<string,string>_defaultHeaders=new();publicHttpPostHelper(){_httpClient=newHttpClient();_httpClient.DefaultRequestHeaders.ExpectContinue=false;_httpClient.DefaultRequestHeaders.ConnectionClose=true;}// 添加全局HeaderpublicvoidAddHeader(stringkey,stringvalue){_defaultHeaders[key]=value;}// 基础POST方法(同步)publicstringPost(stringurl,objectdata=null,ContentTypecontentType=ContentType.Json,stringtoken=null,Encodingencoding=null){varrequest=CreateRequest(url,HttpMethod.Post,data,contentType,token);returnExecuteRequest(request);}// 基础POST方法(异步)publicasyncTask<string>PostAsync(stringurl,objectdata=null,ContentTypecontentType=ContentType.Json,stringtoken=null,Encodingencoding=null){varrequest=CreateRequest(url,HttpMethod.Post,data,contentType,token);returnawaitExecuteRequestAsync(request);}// 文件上传publicasyncTask<HttpResponseMessage>UploadFile(stringurl,stringfilePath,stringfieldName="file",objectformData=null){usingvarcontent=newMultipartFormDataContent();varfileContent=newByteArrayContent(File.ReadAllBytes(filePath));fileContent.Headers.ContentType=MediaTypeHeaderValue.Parse("application/octet-stream");content.Add(fileContent,fieldName,Path.GetFileName(filePath));if(formData!=null){foreach(varpropinformData.GetType().GetProperties()){content.Add(newStringContent(prop.GetValue(formData)?.ToString()??""),prop.Name);}}varresponse=await_httpClient.PostAsync(url,content);response.EnsureSuccessStatusCode();returnresponse;}privateHttpRequestMessageCreateRequest(stringurl,HttpMethodmethod,objectdata,ContentTypecontentType,stringtoken){varrequest=newHttpRequestMessage(method,url);// 设置认证信息if(!string.IsNullOrEmpty(token)){request.Headers.Authorization=newAuthenticationHeaderValue("Bearer",token);}// 合并Headersforeach(varheaderin_defaultHeaders){request.Headers.Add(header.Key,header.Value);}// 处理请求体if(data!=null){varcontent=newStringContent(JsonConvert.SerializeObject(data),Encoding.UTF8);content.Headers.ContentType=MediaTypeHeaderValue.Parse($"application/{contentType}");request.Content=content;}returnrequest;}privatestringExecuteRequest(HttpRequestMessagerequest){try{varresponse=_httpClient.Send(request);response.EnsureSuccessStatusCode();returnresponse.Content.ReadAsStringAsync().Result;}catch(HttpRequestExceptionex){HandleHttpRequestException(ex);returnnull;}}privateasyncTask<string>ExecuteRequestAsync(HttpRequestMessagerequest){try{varresponse=await_httpClient.SendAsync(request);response.EnsureSuccessStatusCode();returnawaitresponse.Content.ReadAsStringAsync();}catch(HttpRequestExceptionex){awaitHandleHttpRequestExceptionAsync(ex);returnnull;}}privatevoidHandleHttpRequestException(HttpRequestExceptionex){// 实现自定义异常处理逻辑Console.WriteLine($"HTTP请求失败:{ex.Message}");}privateasyncTaskHandleHttpRequestExceptionAsync(HttpRequestExceptionex){// 实现异步异常处理逻辑awaitTask.Run(()=>Console.WriteLine($"HTTP请求失败:{ex.Message}"));}}publicenumContentType{Json,FormUrlEncoded,MultipartFormData}

二、核心功能说明

1. 多协议格式支持
// JSON格式varjson=new{Name="Test",Age=30};stringresponse=helper.Post("https://api.example.com",json,ContentType.Json);// 表单格式varformData=new{Username="user",Password="123456"};stringformResponse=helper.Post("https://api.example.com/login",formData,ContentType.FormUrlEncoded);// 文件上传awaithelper.UploadFile("https://api.example.com/upload","test.txt","file",new{description="测试文件"});
2. 安全认证机制
// 添加Bearer Tokenhelper.AddHeader("Authorization","Bearer your_token_here");// 添加自定义认证头helper.AddHeader("X-Api-Key","your_api_key");
3. 高级配置选项
// 配置超时时间helper._httpClient.Timeout=TimeSpan.FromSeconds(30);// 禁用SSL验证(仅测试环境使用)helper._httpClient.DefaultRequestHeaders.Add("Unsafe-SSL","true");

三、扩展功能实现

1. 自定义序列化
publicclassCustomSerializer{publicstaticstringSerialize(objectobj){// 使用System.Text.JsonreturnJsonSerializer.Serialize(obj);// 或使用XmlSerializer// var serializer = new XmlSerializer(obj.GetType());// using var writer = new StringWriter();// serializer.Serialize(writer, obj);// return writer.ToString();}}// 扩展HttpHelperpublicstaticclassHttpPostHelperExtensions{publicstaticstringPostWithCustomSerializer(thisHttpPostHelperhelper,stringurl,objectdata,ContentTypecontentType){varcontent=newStringContent(CustomSerializer.Serialize(data),Encoding.UTF8);content.Headers.ContentType=MediaTypeHeaderValue.Parse($"application/{contentType}");returnhelper.Post(url,data,contentType);}}
2. 自动重试机制
publicstaticclassRetryPolicy{publicstaticasyncTask<string>WithRetry(thisHttpPostHelperhelper,stringurl,Func<Task<string>>action,intmaxRetries=3){intattempt=0;ExceptionlastException=null;do{try{returnawaitaction();}catch(Exceptionex){lastException=ex;attempt++;awaitTask.Delay(TimeSpan.FromSeconds(Math.Pow(2,attempt)));}}while(attempt<maxRetries);thrownewException($"请求失败,已尝试{maxRetries}次",lastException);}}// 使用示例varresult=awaithelper.WithRetry("https://api.example.com",()=>helper.PostAsync("data",retryCount:5));

四、工程实践建议

1. 配置管理
publicclassHttpConfig{publicstringBaseUrl{get;set;}publicintTimeoutSeconds{get;set;}=30;publicboolEnableLogging{get;set;}=true;}// 初始化工具类varconfig=newHttpConfig{BaseUrl="https://api.example.com",TimeoutSeconds=60};varhttpClient=newHttpClient{BaseAddress=newUri(config.BaseUrl),Timeout=TimeSpan.FromSeconds(config.TimeoutSeconds)};
2. 日志记录
publicstaticclassLogger{publicstaticvoidLogRequest(stringmethod,stringurl,objectdata){varlogMessage=$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] "+$"{method}{url}\n"+$"Data:{JsonConvert.SerializeObject(data)}";File.AppendAllText("http.log",logMessage+Environment.NewLine);}}// 在HttpHelper中添加日志publicHttpRequestMessageCreateRequest(stringurl,HttpMethodmethod,objectdata,ContentTypecontentType,stringtoken){Logger.LogRequest(method.ToString(),url,data);// ...原有逻辑}

五、使用示例

varhelper=newHttpPostHelper();helper.AddHeader("X-Custom-Header","CustomValue");// 同步请求varresponse=helper.Post("https://api.example.com/data",new{Id=1,Name="Test"},ContentType.FormUrlEncoded,token:"your_token");// 异步请求awaithelper.PostAsync("https://api.example.com/upload",new{File="test.pdf"},ContentType.MultipartFormData);// 文件上传varuploadResponse=awaithelper.UploadFile("https://api.example.com/upload",@"C:\files\document.pdf","document",new{description="季度报告",projectId=1001});

参考代码 Http的POST万能工具www.youwenfan.com/contentcsv/93248.html

六、扩展建议

  1. 拦截器模式:实现请求/响应拦截器,统一处理认证、日志、缓存
  2. 连接池管理:优化HttpClient连接复用策略
  3. OAuth2支持:集成令牌自动刷新机制
  4. 性能监控:添加请求耗时统计和性能分析
  5. 测试套件:使用xUnit编写单元测试和集成测试
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/18 11:16:09

转行计算机领域——实战应用与学习路径规划

很多刚决定转行做开发的朋友&#xff0c;最容易陷入的误区就是抱着厚厚的教材从第一页啃到最后一页&#xff0c;结果半年过去了&#xff0c;理论背了一堆&#xff0c;连个像样的网页都搭不出来。这种“只输入不输出”的学习方式&#xff0c;在技术迭代如此迅速的今天&#xff0…

作者头像 李华
网站建设 2026/6/18 11:12:02

不用 NVIDIA 也能快,ROCm 7.x 下 vLLM 性能基准测试报告

拒绝“跑分焦虑”&#xff1a;用 benchmark_serving.py 摸清 AMD GPU 的真实性能 很多开发者在把大模型从 NVIDIA 迁移到 AMD Instinct GPU 时&#xff0c;心里总有点打鼓&#xff1a;ROCm 生态到底稳不稳&#xff1f;推理速度会不会崩&#xff1f;其实&#xff0c;光看官方文档…

作者头像 李华
网站建设 2026/6/18 11:11:51

汽车智能制造如何依托数据AI实现生产提质提效

一、汽车智能制造关键在于摆脱经验依赖传统汽车制造依赖人工经验管控、纸质记录、人工复盘的生产模式&#xff0c;存在效率低、误差大、经验难留存等短板。随着工业互联网与人工智能技术深度落地&#xff0c;汽车智能制造彻底打破传统生产局限&#xff0c;依托全流程数字化、数…

作者头像 李华
网站建设 2026/6/18 11:02:12

网页游戏动画教学:基础知识试卷-第一部分-由Deepseek产生

好的&#xff0c;理解您的要求。我重新为您设计了三套难度完全一致的试卷&#xff0c;每套试卷中基础题占比80%&#xff08;即24道单选、8道多选、8道是非考察核心基础概念&#xff09;&#xff0c;其余20%为略有提升的运用或辨析题&#xff0c;但整体难度保持在同一水平。三套…

作者头像 李华
网站建设 2026/6/18 10:58:15

全星研发项目管理APQP软件系统,赋能车企零部件新品合规研发

全星研发项目管理APQP软件系统&#xff0c;赋能车企零部件新品合规研发车企、零部件及高端制造企业采购APQP研发管理系统&#xff0c;核心聚焦合规适配、流程闭环、互联互通、投入性价比、运维保障五大评估维度&#xff0c;市面上多数通用项目软件难以贴合IATF16949行业标准&am…

作者头像 李华