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

相关推荐
天马37984 小时前
.net 8.0 System.InvalidOperationException:“Session has not been configured
.net
-可乐加冰吗12 小时前
SuperMap iObjects .NET 11i 二次开发(十七)—— 叠加分析之擦除
windows·.net
一抓掉一大把12 小时前
RuoYi .net-实现商城秒杀下单(redis,rabbitmq)
redis·mysql·c#·rabbitmq·.net
缺点内向19 小时前
C#: 高效移动与删除Excel工作表
开发语言·c#·.net·excel
一抓掉一大把1 天前
.net实现秒杀商品(Redis高并发)
.net
mudtools1 天前
解放双手!使用Roslyn生成代码让你的 HTTP 客户端开发变得如此简单
低代码·c#·.net
主宰者2 天前
WPF CalcBinding简化判断逻辑
c#·.net·wpf
【D'accumulation】2 天前
.NET Framework 4.8 + Microsoft.Data.Sqlite 报 Library e_sqlite3 not found
microsoft·sqlite·.net
数据的世界012 天前
技术变革:为何C#与.NET是未来的开发方向
java·c#·.net