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

相关推荐
江沉晚呤时6 小时前
C# 整型溢出处理机制:checked 与 unchecked 上下文解析
c#·.net
余衫马7 小时前
在 Windows 服务中托管 ASP.NET Core Web API (.net6)
运维·windows·后端·asp.net·.net
步步为营DotNet9 小时前
LM-Kit.NET:.NET 生态一站式本地 AI 开发平台
人工智能·.net
步步为营DotNet9 小时前
.NET 实战 LlamaSharp:本地运行开源大模型
.net
CSharp精选营10 小时前
推荐一个开箱即用的.NET权限管理平台:Magic.NET
.net·开源项目·权限管理·企业级框架·后台脚手架
切糕师学AI1 天前
.NET CLR GC 调优完全指南:从理论到生产实战
.net·gc·clr
唐青枫1 天前
C#.NET TaskCompletionSource 深入解析:手动控制 Task、桥接回调事件与实战避坑
c#·.net
OctShop大型商城源码1 天前
C#.NET多商户商城系统源码_OctShop:技术与机遇的融合
c#·.net·多商户商城系统源码·商城系统源码
编码者卢布1 天前
【App Service】常规排查 App Service 启动 Application Insights 无数据的步骤 (.NET版本)
python·flask·.net
rockey6272 天前
AScript函数体系详解
c#·.net·script·eval·expression·function·动态脚本