当前位置: 首页 > news >正文

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

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


一、核心工具类实现

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;public class HttpPostHelper
{private readonly HttpClient _httpClient;private readonly Dictionary<string, string> _defaultHeaders = new();public HttpPostHelper(){_httpClient = new HttpClient();_httpClient.DefaultRequestHeaders.ExpectContinue = false;_httpClient.DefaultRequestHeaders.ConnectionClose = true;}// 添加全局Headerpublic void AddHeader(string key, string value){_defaultHeaders[key] = value;}// 基础POST方法(同步)public string Post(string url, object data = null,ContentType contentType = ContentType.Json,string token = null,Encoding encoding = null){var request = CreateRequest(url, HttpMethod.Post, data, contentType, token);return ExecuteRequest(request);}// 基础POST方法(异步)public async Task<string> PostAsync(string url,object data = null,ContentType contentType = ContentType.Json,string token = null,Encoding encoding = null){var request = CreateRequest(url, HttpMethod.Post, data, contentType, token);return await ExecuteRequestAsync(request);}// 文件上传public async Task<HttpResponseMessage> UploadFile(string url,string filePath,string fieldName = "file",object formData = null){using var content = new MultipartFormDataContent();var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");content.Add(fileContent, fieldName, Path.GetFileName(filePath));if (formData != null){foreach (var prop in formData.GetType().GetProperties()){content.Add(new StringContent(prop.GetValue(formData)?.ToString() ?? ""),prop.Name);}}var response = await _httpClient.PostAsync(url, content);response.EnsureSuccessStatusCode();return response;}private HttpRequestMessage CreateRequest(string url,HttpMethod method,object data,ContentType contentType,string token){var request = new HttpRequestMessage(method, url);// 设置认证信息if (!string.IsNullOrEmpty(token)){request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);}// 合并Headersforeach (var header in _defaultHeaders){request.Headers.Add(header.Key, header.Value);}// 处理请求体if (data != null){var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8);content.Headers.ContentType = MediaTypeHeaderValue.Parse($"application/{contentType}");request.Content = content;}return request;}private string ExecuteRequest(HttpRequestMessage request){try{var response = _httpClient.Send(request);response.EnsureSuccessStatusCode();return response.Content.ReadAsStringAsync().Result;}catch (HttpRequestException ex){HandleHttpRequestException(ex);return null;}}private async Task<string> ExecuteRequestAsync(HttpRequestMessage request){try{var response = await _httpClient.SendAsync(request);response.EnsureSuccessStatusCode();return await response.Content.ReadAsStringAsync();}catch (HttpRequestException ex){await HandleHttpRequestExceptionAsync(ex);return null;}}private void HandleHttpRequestException(HttpRequestException ex){// 实现自定义异常处理逻辑Console.WriteLine($"HTTP请求失败: {ex.Message}");}private async Task HandleHttpRequestExceptionAsync(HttpRequestException ex){// 实现异步异常处理逻辑await Task.Run(() => Console.WriteLine($"HTTP请求失败: {ex.Message}"));}
}public enum ContentType
{Json,FormUrlEncoded,MultipartFormData
}

二、核心功能说明

1. 多协议格式支持

// JSON格式
var json = new { Name = "Test", Age = 30 };
string response = helper.Post("https://api.example.com", json, ContentType.Json);// 表单格式
var formData = new { Username = "user", Password = "123456" };
string formResponse = helper.Post("https://api.example.com/login", formData, ContentType.FormUrlEncoded);// 文件上传
await helper.UploadFile("https://api.example.com/upload", "test.txt", "file", new { description = "测试文件" });

2. 安全认证机制

// 添加Bearer Token
helper.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. 自定义序列化

public class CustomSerializer
{public static string Serialize(object obj){// 使用System.Text.Jsonreturn JsonSerializer.Serialize(obj);// 或使用XmlSerializer// var serializer = new XmlSerializer(obj.GetType());// using var writer = new StringWriter();// serializer.Serialize(writer, obj);// return writer.ToString();}
}// 扩展HttpHelper
public static class HttpPostHelperExtensions
{public static string PostWithCustomSerializer(this HttpPostHelper helper, string url, object data,ContentType contentType){var content = new StringContent(CustomSerializer.Serialize(data), Encoding.UTF8);content.Headers.ContentType = MediaTypeHeaderValue.Parse($"application/{contentType}");return helper.Post(url, data, contentType);}
}

2. 自动重试机制

public static class RetryPolicy
{public static async Task<string> WithRetry(this HttpPostHelper helper, string url, Func<Task<string>> action,int maxRetries = 3){int attempt = 0;Exception lastException = null;do{try{return await action();}catch (Exception ex){lastException = ex;attempt++;await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));}} while (attempt < maxRetries);throw new Exception($"请求失败,已尝试 {maxRetries} 次", lastException);}
}// 使用示例
var result = await helper.WithRetry("https://api.example.com", () => helper.PostAsync("data", retryCount: 5));

四、工程实践建议

1. 配置管理

public class HttpConfig
{public string BaseUrl { get; set; }public int TimeoutSeconds { get; set; } = 30;public bool EnableLogging { get; set; } = true;
}// 初始化工具类
var config = new HttpConfig
{BaseUrl = "https://api.example.com",TimeoutSeconds = 60
};var httpClient = new HttpClient
{BaseAddress = new Uri(config.BaseUrl),Timeout = TimeSpan.FromSeconds(config.TimeoutSeconds)
};

2. 日志记录

public static class Logger
{public static void LogRequest(string method, string url, object data){var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] " +$"{method} {url}\n" +$"Data: {JsonConvert.SerializeObject(data)}";File.AppendAllText("http.log", logMessage + Environment.NewLine);}
}// 在HttpHelper中添加日志
public HttpRequestMessage CreateRequest(string url, HttpMethod method, object data, ContentType contentType, string token)
{Logger.LogRequest(method.ToString(), url, data);// ...原有逻辑
}

五、使用示例

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

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

六、扩展建议

  1. 拦截器模式:实现请求/响应拦截器,统一处理认证、日志、缓存
  2. 连接池管理:优化HttpClient连接复用策略
  3. OAuth2支持:集成令牌自动刷新机制
  4. 性能监控:添加请求耗时统计和性能分析
  5. 测试套件:使用xUnit编写单元测试和集成测试
http://www.rkmt.cn/news/120928.html

相关文章:

  • EmotiVoice语音合成引擎的国际化部署建议
  • 2025年年终上海管道疏通推荐:权威榜单解析与专业服务对比评测 - 十大品牌推荐
  • 6-9 WPS JS宏Map、 set、get、delete、clear()映射的添加、修改、删除
  • 2025年12月包头钢结构/钢结构厂房/建筑钢结构/厂家深度分析 - 2025年品牌推荐榜
  • 国产化Excel开发组件Spire.XLS教程:以Python编程方式在Excel中高亮重复值
  • 聚焦2025:十大备受推崇的BIP管理平台横向评测,好生意/好会计/易代账/制造云/好业财/协同云/供应链云/人力云BIP服务商推荐排行榜 - 品牌推荐师
  • Excel处理控件Aspose.Cells教程:使用C#在Excel中创建树状图
  • web宠物猫认养系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
  • Kotaemon日历事件管理:创建提醒与预约
  • 【CAOA三维路径规划】鳄鱼伏击算法CAOA多无人机协同集群避障路径规划(目标函数:最低成本:路径、高度、威胁、转角)【含Matlab源码 14723期】
  • GPT-5.2并非全面升级,OneEval V1.3 最新“LLM+KB”评测结果出炉
  • RabbitMQ入门第一课:消息队列是什么?解决分布式系统哪些痛点?
  • KotaemonSlogan创意生成:品牌口号工厂
  • 计算机中浮点数的存储
  • 腾讯混元这次开源太狠了!把AI视频变成了用户可操控的“开放世界”。(附实操体验)
  • 四川润明启青少年心理行为训练机构联系方式:使用指南与注意事项 - 十大品牌推荐
  • 2025年年终跨境物流公司推荐排行榜:十家服务商详细对比与选择指南 - 十大品牌推荐
  • 12、Ourmon:网络监控与异常检测工具全解析
  • 慧荣SM768应用于USB转HDMI 4K+VGA/HDMI 1080p双屏显示方案设计资料
  • Kotaemon ONNX Runtime集成:跨平台高性能执行
  • 复杂时序场景的突围:金仓数据库是凭借什么超越InfluxDB?
  • 使用 Python 进行预期改进和高斯过程回归的动手优化
  • 2025年五大二手发电机组回收公司推荐:二手发电机组回收制造 - 工业推荐榜
  • 彻底告别VAE!清华x可灵联手开源SVG-T2I:生成理解合二为一,性能媲美SD3
  • 2025年江苏叉车司机培训公司权威推荐榜单:叉车培训考试/开叉车培训/叉车驾驶员培训精选 - 品牌推荐官
  • 特价股票投资中的跨境投资策略与风险管理
  • 2025年太阳能路灯推荐品牌解析:聚焦太阳能路灯节能环保效果 - 工业品牌热点
  • 28、在AWS和GCP上部署和升级Kubernetes
  • 29、在GCP上部署Kubernetes:负载均衡、持久磁盘与集群搭建全攻略
  • 8个AI论文工具,继续教育学员快速完成写作!