.net HttpClient封装

csharp 复制代码
using Newtonsoft.Json;
/// <summary>
/// Http 请求工具类
/// </summary>
public class HttpClientUtils
{
/// <summary>
/// 请求的域名
/// </summary>
public static string BaseUrl { get; set; } = "http://localhost:5016";
/// <summary>
/// 发送Get请求
/// </summary>
/// <param name="url">请求地址(包含请求的参数信息)</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T? Get<T>(string url)
{
using HttpClient client = new HttpClient();
if (String.IsNullOrWhiteSpace(BaseUrl))
{
throw new Exception("请先设置BaseUrl请求的域名");
}
// 设置
client.BaseAddress = new Uri(BaseUrl);
// 创建请求对象
var request = new HttpRequestMessage(HttpMethod.Get,url);
var response = client.Send(request); // 发送请求,得到响应对象
var json = response.Content.ReadAsStringAsync().Result;
if (string.IsNullOrWhiteSpace(json))
{
return default;
}
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// 发送Post请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="parms">请求参数</param>
/// <typeparam name="T">返回值类型</typeparam>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static T? Post<T>(string url, object parms)
{
using HttpClient client = new HttpClient();
if (String.IsNullOrWhiteSpace(BaseUrl))
{
throw new Exception("请先设置BaseUrl请求的域名");
}
// 设置
client.BaseAddress = new Uri(BaseUrl);
using HttpContent httpContent = new
StringContent(JsonConvert.SerializeObject(parms),
Encoding.UTF8,"application/json");
HttpResponseMessage response = client.PostAsync(url,
httpContent).Result;
var result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result);
}
}

.net HttpClient封装

相关推荐
心念枕惊7 小时前
OpenClaw.NET 重大更新:Goal 机制登场,让 AI Agent 不再“半途而废“
.net
geovindu8 小时前
CSharp:Chain of Responsibility Pattern
开发语言·后端·设计模式·c#·.net·责任链模式·行为模式
TDengine (老段)10 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
逻极2 天前
C# 从入门到精通:现代云原生与AI应用开发实战
ai·云原生·c#·.net
geovindu2 天前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
海盗12343 天前
微软技术周报2026-07-27
microsoft·c#·.net
iReachers3 天前
.NET项目集成混淆加密:自动化保护DLL和EXE
.net·代码保护·自动构建·msbuild·c#混淆
完美火龙篇 四月的友3 天前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
柠檬香的4 天前
CsGrafeq: 比 Desmos 更“能折腾”的几何函数画板(.NET + Avalonia)
.net