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

C# HttpHelper 类

using System;
using System.Net.Http;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;public class VipSoftHttpHelper
{private readonly HttpClient _httpClient;private VipSoftHttpHelper() {_httpClient = new HttpClient(new HttpClientHandler(){UseProxy = false,// 其他配置...});_httpClient.DefaultRequestHeaders.Add("User-Agent", "C#-Client");}private static readonly Lazy<VipSoftHttpHelper> instance = new Lazy<VipSoftHttpHelper>(() => new VipSoftHttpHelper());public static VipSoftHttpHelper Instance => instance.Value;/// <summary>/// POST 请求 Java API 接口/// </summary>/// <param name="url">请求地址</param>/// <param name="postData">请求数据对象</param>/// <param name="timeoutSeconds">超时时间(秒)</param>/// <param name="headers">请求头</param>/// <returns>响应字符串</returns>public string HttpPost(string url, object postData, int timeoutSeconds = 30, Dictionary<string, string> headers = null){try{// 序列化数据string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(postData);LogHelper.Debug($"HTTP POST: {url}, Timeout: {timeoutSeconds}s, Data: {jsonContent}");// 使用 HttpRequestMessage 而不是直接修改 HttpClientvar request = new HttpRequestMessage(HttpMethod.Post, url){Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")};// 添加自定义请求头到本次请求if (headers != null){foreach (var header in headers){if (header.Key.ToLower() == "content-type")continue;request.Headers.TryAddWithoutValidation(header.Key, header.Value);}}// 使用 CancellationToken 实现超时CancellationTokenSource cts = new CancellationTokenSource();try{if (timeoutSeconds > 0){ cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); // 兼容旧版本}// 发送请求HttpResponseMessage response = _httpClient.SendAsync(request, cts.Token).Result;// 确保请求成功response.EnsureSuccessStatusCode();// 读取响应内容return response.Content.ReadAsStringAsync().Result;}finally{cts?.Dispose();}}catch (AggregateException ae){throw ae.InnerException ?? ae;}catch (TaskCanceledException) when (timeoutSeconds > 0){throw new TimeoutException($"请求超时 ({timeoutSeconds}秒)");}}/// <summary>/// 带泛型返回值的 POST 请求/// </summary>public T HttpPost<T>(string url, object postData, int timeoutSeconds = 30, Dictionary<string, string> headers = null){string responseJson = HttpPost(url, postData, timeoutSeconds, headers);return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseJson);}/// <summary>/// GET 请求/// </summary>public string HttpGet(string url, int timeoutSeconds = 30, Dictionary<string, string> headers = null){try{// 使用 HttpRequestMessage 而不是直接修改 HttpClient var request = new HttpRequestMessage(HttpMethod.Get, url); // 添加自定义请求头到本次请求if (headers != null){foreach (var header in headers){if (header.Key.ToLower() == "content-type")continue;request.Headers.TryAddWithoutValidation(header.Key, header.Value);}}// 使用 CancellationToken 实现超时CancellationTokenSource cts = new CancellationTokenSource();try{if (timeoutSeconds > 0){cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); // 兼容旧版本}// 发送请求HttpResponseMessage response = _httpClient.SendAsync(request, cts.Token).Result;// 确保请求成功response.EnsureSuccessStatusCode();// 读取响应内容return response.Content.ReadAsStringAsync().Result;}finally{cts?.Dispose();}}catch (AggregateException ae){throw ae.InnerException ?? ae;}catch (TaskCanceledException) when (timeoutSeconds > 0){throw new TimeoutException($"请求超时 ({timeoutSeconds}秒)");}}/// <summary>/// 带泛型返回值的 GET 请求/// </summary>public T HttpGet<T>(string url, int timeoutSeconds = 30, Dictionary<string, string> headers = null){string responseJson = HttpGet(url, timeoutSeconds, headers);return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseJson);}
}

✅ 代码优点
线程安全:使用 HttpRequestMessage 避免共享状态问题
兼容性好:使用 CancelAfter 兼容旧版 .NET Framework
资源管理:正确使用 try-finally 释放 CancellationTokenSource
异常处理:区分超时异常和其他异常
单例模式:正确复用 HttpClient 实例

http://www.zskr.cn/news/52667.html

相关文章:

  • 2025年靠谱的光学器件ALD人气推荐榜
  • 2025年靠谱的机器人编程招商行业热点榜
  • linux .bz2
  • 2025年知名的餐饮品牌设计实测推荐榜
  • 2025年比较好的二轴程控平面磨床厂家最新推荐排行榜
  • 2025年热门的移动式港口起重机厂家推荐及选购参考榜
  • linux -c 参数
  • linux - generic
  • linux $line
  • linux 代表什么意思
  • AI元人文实践:价值原语化——法律法规代码化(整合)
  • left函数sql的最佳实践有哪些
  • Kylin SQL性能优化怎么做
  • kali linux输入中文
  • kali linux 网卡
  • kali linux 上网
  • 20251117 之所思 - 人生如梦
  • jstack for linux
  • 20251103 - Balancer 攻击事件:还是 batchSwap,还是价格操纵+精度丢失
  • Thinking
  • jdk 1.7 linux 安装
  • 网络分析模型十
  • 251117
  • 合并和部分保存与鼠标的使用
  • 打开保存各种格式文件
  • FunASR 快速上手
  • JDBC与MySQL交互有哪些安全措施
  • 网络分析模型八
  • java执行linux 命令
  • 绘图区右键上下文菜单快捷键设置