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

相关推荐
Jeff-Tsai18 小时前
Day 24:权限的三轴:动作、行与列
.net·架构设计·erp·definition-driven
BruceNeter19 小时前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
Jeff-Tsai2 天前
Day 23:API Payload 安全管道:顺序、保护等级与密钥
.net·架构设计·erp·definition-driven
IT规划师2 天前
Redis 核心机制 | 内存淘汰策略全解:8种策略、近似LRU采样、LFU计数器
redis·.net
Jeff-Tsai3 天前
Day 22:XML、JSON 与 MessagePack 的分工
.net·架构设计·erp·definition-driven
风云4 天前
从 NLite 到 Vane.Container 1.0:压箱十六年的自研 DI 容器开源
.net·di·mini 容器·nlite
Jeff-Tsai4 天前
Day 21:业务逻辑定制与 Plugin 的四个时点
.net·架构设计·erp·definition-driven
IT规划师4 天前
Redis 核心机制 | 键生命周期与 TTL 管理
redis·.net