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

相关推荐
唐青枫13 小时前
C#.NET log4net 详解
c#·.net
ChaITSimpleLove1 天前
使用 Dockerfile 构建基于 .NET9 的跨平台基础镜像
.net·dockerfile·.net aspire·dotnet-sdk·pwsh·docker image·docker buildx
专注VB编程开发20年1 天前
C#,VB.NET从JSON数据里提取数组中的对象节点值
c#·json·.net
界面开发小八哥1 天前
界面组件DevExpress WPF中文教程:Grid - 如何获取节点?
.net·wpf·界面控件·devexpress·ui开发
今晚打老虎z1 天前
dotnet-env: .NET 开发者的环境变量加载工具
前端·chrome·.net
我是唐青枫1 天前
C#.NET NLog 详解
开发语言·c#·.net
一线码农2 天前
MinHook 如何对 .NET 母体 CoreCLR 进行拦截
c#·.net·代码注入
佛·追命2 天前
.net wpf混淆
.net·wpf
编程乐趣2 天前
自学C#,要懂得用好对象浏览器
windows·.net