.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封装

相关推荐
rockey6273 小时前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
半亩码田5 小时前
【.NET新特性·第11篇】C# 14 字段属性:告别手写 backing field
java·c#·.net
唐青枫8 小时前
别再把命令行参数写成一团:C#.NET System.CommandLine 实战详解
c#·.net
hez20108 小时前
让 .NET 11 的泛型虚方法变得更快!
c#·.net·.net core·clr·compiler
宝桥南山9 小时前
Microsoft Agent Framework(.NET) - 尝试一下从MCP Server上获取Agent Skills
ai·微软·c#·aigc·.net·.netcore
海盗123414 小时前
微软技术日报·2026-08-12——Windows 11多通道累积更新推送十余项功能改进;.NET WebSocket DoS紧急修复
windows·microsoft·.net
唐青枫1 天前
别再手写 args[0]:C#.NET CommandLineParser 命令行工具实战详解
c#·.net
.Peter2 天前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
MyBili2 天前
游戏报错缺少dll、无法启动?GRLPackage 运行库合集一键修复指南
游戏·.net·directx·运行库·xna·openal·vc++ redis
慧都小妮子2 天前
PDF图片提取总“褪色“?Aspose.PDF 多层级提取能力详解
pdf·c#·.net·图片处理·文档处理·色彩空间