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;privatereadonlyDictionarystring,string_defaultHeadersnew();publicHttpPostHelper(){_httpClientnewHttpClient();_httpClient.DefaultRequestHeaders.ExpectContinuefalse;_httpClient.DefaultRequestHeaders.ConnectionClosetrue;}// 添加全局HeaderpublicvoidAddHeader(stringkey,stringvalue){_defaultHeaders[key]value;}// 基础POST方法同步publicstringPost(stringurl,objectdatanull,ContentTypecontentTypeContentType.Json,stringtokennull,Encodingencodingnull){varrequestCreateRequest(url,HttpMethod.Post,data,contentType,token);returnExecuteRequest(request);}// 基础POST方法异步publicasyncTaskstringPostAsync(stringurl,objectdatanull,ContentTypecontentTypeContentType.Json,stringtokennull,Encodingencodingnull){varrequestCreateRequest(url,HttpMethod.Post,data,contentType,token);returnawaitExecuteRequestAsync(request);}// 文件上传publicasyncTaskHttpResponseMessageUploadFile(stringurl,stringfilePath,stringfieldNamefile,objectformDatanull){usingvarcontentnewMultipartFormDataContent();varfileContentnewByteArrayContent(File.ReadAllBytes(filePath));fileContent.Headers.ContentTypeMediaTypeHeaderValue.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);}}varresponseawait_httpClient.PostAsync(url,content);response.EnsureSuccessStatusCode();returnresponse;}privateHttpRequestMessageCreateRequest(stringurl,HttpMethodmethod,objectdata,ContentTypecontentType,stringtoken){varrequestnewHttpRequestMessage(method,url);// 设置认证信息if(!string.IsNullOrEmpty(token)){request.Headers.AuthorizationnewAuthenticationHeaderValue(Bearer,token);}// 合并Headersforeach(varheaderin_defaultHeaders){request.Headers.Add(header.Key,header.Value);}// 处理请求体if(data!null){varcontentnewStringContent(JsonConvert.SerializeObject(data),Encoding.UTF8);content.Headers.ContentTypeMediaTypeHeaderValue.Parse($application/{contentType});request.Contentcontent;}returnrequest;}privatestringExecuteRequest(HttpRequestMessagerequest){try{varresponse_httpClient.Send(request);response.EnsureSuccessStatusCode();returnresponse.Content.ReadAsStringAsync().Result;}catch(HttpRequestExceptionex){HandleHttpRequestException(ex);returnnull;}}privateasyncTaskstringExecuteRequestAsync(HttpRequestMessagerequest){try{varresponseawait_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格式varjsonnew{NameTest,Age30};stringresponsehelper.Post(https://api.example.com,json,ContentType.Json);// 表单格式varformDatanew{Usernameuser,Password123456};stringformResponsehelper.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.TimeoutTimeSpan.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){varcontentnewStringContent(CustomSerializer.Serialize(data),Encoding.UTF8);content.Headers.ContentTypeMediaTypeHeaderValue.Parse($application/{contentType});returnhelper.Post(url,data,contentType);}}2. 自动重试机制publicstaticclassRetryPolicy{publicstaticasyncTaskstringWithRetry(thisHttpPostHelperhelper,stringurl,FuncTaskstringaction,intmaxRetries3){intattempt0;ExceptionlastExceptionnull;do{try{returnawaitaction();}catch(Exceptionex){lastExceptionex;attempt;awaitTask.Delay(TimeSpan.FromSeconds(Math.Pow(2,attempt)));}}while(attemptmaxRetries);thrownewException($请求失败已尝试{maxRetries}次,lastException);}}// 使用示例varresultawaithelper.WithRetry(https://api.example.com,()helper.PostAsync(data,retryCount:5));四、工程实践建议1. 配置管理publicclassHttpConfig{publicstringBaseUrl{get;set;}publicintTimeoutSeconds{get;set;}30;publicboolEnableLogging{get;set;}true;}// 初始化工具类varconfignewHttpConfig{BaseUrlhttps://api.example.com,TimeoutSeconds60};varhttpClientnewHttpClient{BaseAddressnewUri(config.BaseUrl),TimeoutTimeSpan.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,logMessageEnvironment.NewLine);}}// 在HttpHelper中添加日志publicHttpRequestMessageCreateRequest(stringurl,HttpMethodmethod,objectdata,ContentTypecontentType,stringtoken){Logger.LogRequest(method.ToString(),url,data);// ...原有逻辑}五、使用示例varhelpernewHttpPostHelper();helper.AddHeader(X-Custom-Header,CustomValue);// 同步请求varresponsehelper.Post(https://api.example.com/data,new{Id1,NameTest},ContentType.FormUrlEncoded,token:your_token);// 异步请求awaithelper.PostAsync(https://api.example.com/upload,new{Filetest.pdf},ContentType.MultipartFormData);// 文件上传varuploadResponseawaithelper.UploadFile(https://api.example.com/upload,C:\files\document.pdf,document,new{description季度报告,projectId1001});参考代码 Http的POST万能工具www.youwenfan.com/contentcsv/93248.html六、扩展建议拦截器模式实现请求/响应拦截器统一处理认证、日志、缓存连接池管理优化HttpClient连接复用策略OAuth2支持集成令牌自动刷新机制性能监控添加请求耗时统计和性能分析测试套件使用xUnit编写单元测试和集成测试