webApi请求封装-----仅借鉴
using Newtonsoft.Json;
using NLog;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
namespace YiBo.PMS.CenterAgentApi.Common
{
/// <summary>
/// Web通用帮助类
/// </summary>
public class HttpWebClientHelper
{
private readonly IHttpClientFactory _httpClientFactory;
public HttpWebClientHelper(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
#region WebPost异步请求
/// <summary>
/// WebPost异步请求返回string
/// </summary>
public async Task<string> PostAsync(string url, string json, Dictionary<string, string>? headers = null, int timeOut = 60, string bodyMediaType = "application/json", string responseContentType = "")
{
var result = "";
try
{
using (var client = _httpClientFactory.CreateClient())
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers is { Count: > 0 })
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
client.DefaultRequestHeaders.ConnectionClose = true;//短连接
var content = new StringContent(json, Encoding.UTF8, bodyMediaType);
if (!string.IsNullOrWhiteSpace(responseContentType))
{
content.Headers.ContentType = MediaTypeHeaderValue.Parse(responseContentType);
}
using (var response = await client.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return result;
}
result = await response.Content.ReadAsStringAsync();
return result;
}
}
}
catch (Exception e)
{
//记录参数
NLogHelper.WriteFileLog(LogLevel.Error, LogType.Web, "PostException", $"地址{url}----请求参数{json}----响应参数{result}----错误信息{e.Message}");
throw new Exception($"发生错误{e.Message}");
}
}
/// <summary>
/// WebPost异步请求返回实体
/// </summary>
public async Task<T?> PostAsync<T>(string url, string json, Dictionary<string, string>? headers = null, int timeOut = 60, string bodyMediaType = "application/json", string responseContentType = "") where T : class, new()
{
GC.Collect();//垃圾回收,回收没有正常关闭的http连接
var result = "";
try
{
using (var client = _httpClientFactory.CreateClient())
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers is { Count: > 0 })
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
client.DefaultRequestHeaders.ConnectionClose = true;//短连接
var content = new StringContent(json, Encoding.UTF8, bodyMediaType);
if (!string.IsNullOrWhiteSpace(responseContentType))
{
content.Headers.ContentType = MediaTypeHeaderValue.Parse(responseContentType);
}
using (var response = await client.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(result) ? JsonConvert.DeserializeObject<T>(result) : null;
}
result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result);
}
}
}
catch (Exception e)
{
//记录参数
NLogHelper.WriteFileLog(LogLevel.Error, LogType.Web, "PostException", $"地址{url}----请求参数{json}----响应参数{result}----错误信息{e.Message}");
throw new Exception($"发生错误{e.Message}");
}
}
#endregion
#region WebGet异步请求
/// <summary>
/// WebGet异步请求返回string
/// </summary>
public async Task<string> GetAsync(string url, Dictionary<string, string>? headers = null, int timeOut = 60)
{
var result = "";
try
{
using (var client = _httpClientFactory.CreateClient())
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers is { Count: > 0 })
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
client.DefaultRequestHeaders.ConnectionClose = true;//短连接
using (var response = await client.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return result;
}
result = await response.Content.ReadAsStringAsync();
return result;
}
}
}
catch (WebException e)
{
//记录参数
NLogHelper.WriteFileLog(LogLevel.Error, LogType.Web, "GetException", $"地址{url}----响应参数{result}----错误信息{e.Message}");
throw new Exception($"发生错误{e.Message}");
}
}
/// <summary>
/// WebGet异步请求返回实体
/// </summary>
/// <param name="headers">头部信息</param>
/// <param name="url">请求地址</param>
/// <returns></returns>
public async Task<T?> GetAsync<T>(string url, Dictionary<string, string>? headers = null, int timeOut = 60) where T : class, new()
{
GC.Collect();//垃圾回收,回收没有正常关闭的http连接
var result = "";
try
{
using (var client = _httpClientFactory.CreateClient())
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers is { Count: > 0 })
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
client.DefaultRequestHeaders.ConnectionClose = true;//短连接
using (var response = await client.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(result) ? JsonConvert.DeserializeObject<T>(result) : null;
}
result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result);
}
}
}
catch (Exception e)
{
//记录参数
NLogHelper.WriteFileLog(LogLevel.Error, LogType.Web, "GetException", $"地址{url}----响应参数{result}----错误信息{e.Message}");
throw new Exception($"发生错误{e.Message}");
}
}
#endregion
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)