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

相关推荐
Java资深爱好者9 小时前
VB.NET中如何利用ASP.NET进行Web开发
前端·asp.net·.net
Lingbug12 小时前
.Net日志组件之NLog的使用和配置
后端·c#·.net·.netcore
那个那个鱼21 小时前
.NET 框架版本年表
开发语言·c#·.net
小乖兽技术1 天前
fo-dicom,第一个基于.NET Standard 2.0 开发的DICOM开源库
.net·fo-dicom
nigture1 天前
.NET全局静态可访问IServiceProvider(支持Blazor)
.net·ioc·di·rougamo
脚步的影子2 天前
.NET 6.0 + WPF 使用 Prism 框架实现导航
.net·wpf
wo63704312 天前
[Visual Stuidio 2022使用技巧]2.配置及常用快捷键
c#·.net·wpf
界面开发小八哥3 天前
DevExpress WPF中文教程:如何解决排序、过滤遇到的常见问题?(二)
.net·wpf·界面控件·devexpress·ui开发
平凡而伟大(心之所向)3 天前
关于.net Framework向.net core的移植
java·.net·.netcore