ASP.NET Core使用HttpClient的同步和异步请求
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Common { /// <summary> /// 注意:HttpCient存在缺陷,高并发情况下会存在大量处于TIME_WAIT状态的套接字资源 /// 因此可能造成套接字资源被耗尽,将抛出SocketException 错误。 /// 高并发项目建议使用IHttpClientFactory或者HttpWebRequest实现 /// </summary> public class HttpHelper { /// <summary> /// 发起POST同步请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="body">POST提交的内容</param> /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded等</param> /// <param name="headers">请求头</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static string HttpPost(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30) { body = body ?? ""; using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } using (HttpContent httpContent = new StringContent(body, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } } } /// <summary> /// 发起POST异步请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="body">POST提交的内容</param> /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param> /// <param name="headers">填充消息头</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static async Task<string> HttpPostAsync(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30) { body = body ?? ""; using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } using (HttpContent httpContent = new StringContent(body, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent); return await response.Content.ReadAsStringAsync(); } } } /// <summary> /// 发起GET同步请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="headers">请求头</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static string HttpGet(string url, Dictionary<string, string> headers = null, int timeOut = 30) { using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = client.GetAsync(url).Result; return response.Content.ReadAsStringAsync().Result; } } /// <summary> /// 发起GET异步请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="headers">请求头</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null, int timeOut = 30) { using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } } } }
调用方法:
var headers = new Dictionary<string, string>(); headers.Add("authorization", "eyJhbGciOiJodHRwOi8vd3d3LnczLXXXXXXX……"); var result = await HttpHelper.HttpPostAsync(url, "{\"name\"=\"铁柱\"}", "application/json", headers, 30);
使用IHttpClientFactory发起Http请求,请参考:
https://www.cnblogs.com/pudefu/p/14715146.html
分类:
ASP.NET Core
标签:
.NET Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧