当前位置: 首页 > 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.jsqmd.com/news/43224/

相关文章:

  • 2025年高中学习机推荐:5款提分学习工具,助力孩子学习!
  • 2025年靠谱的光学器件ALD人气推荐榜
  • 2025年靠谱的机器人编程招商行业热点榜
  • 2025年比较好的机器人编程机构附近机构推荐
  • 从「跨模态思维链」到「物理 AI 数据闭环」:下一代多模态技术和落地丨多模态技术专场@RTE2025 回顾
  • 【GitHub每日速递 20251118】30秒极速部署,TrendRadar带你告别无效刷屏,精准掌控全网热点!
  • 2025年评价高的ALD热门实力榜
  • 2025年靠谱的远程医疗查房系统品牌精选榜
  • 2025.11.18——1绿
  • 2025年知名的远程医疗查房系统平台推荐榜
  • 2025年知名的粉末冶金齿轮厂家推荐及采购指南
  • linux .bz2
  • linux .bash profile
  • 2025年热门的连锁餐饮品牌设计综合实力榜
  • 2025年知名的餐饮品牌设计实测推荐榜
  • 2025年热门的金属退火丝最新TOP品牌厂家排行
  • 2025年口碑好的精密平面磨床厂家最新推荐权威榜
  • 2025年知名的黑色退火丝厂家最新推荐权威榜
  • 读社会工程:安全体系中的人性漏洞(第2版)05发起攻击
  • 2025年比较好的二轴程控平面磨床厂家最新推荐排行榜
  • 2025年知名的精密平面磨床高评价厂家推荐榜
  • 2025年热门的移动式港口起重机厂家推荐及选购参考榜
  • 2025年评价高的桥门式起重机用户好评厂家排行
  • 2025年知名的液压油缸品牌厂家排行榜
  • 2025年热门的卧轴矩台平面磨床用户口碑最好的厂家榜
  • 2025年比较好的柱塞式液压油缸厂家最新权威实力榜
  • linux -c 参数
  • linux - generic
  • linux $term
  • linux $line