.net HttpClient封装

using Newtonsoft.Json;
/// 
/// Http 请求工具类
/// 
public class HttpClientUtils
{
/// 
/// 请求的域名
/// 
public static string BaseUrl { get; set; } = "http://localhost:5016";
/// 
/// 发送Get请求
/// 
/// 请求地址(包含请求的参数信息)
/// 
/// 
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);
}
/// 
/// 发送Post请求
/// 
/// 请求地址
/// 请求参数
/// 返回值类型
/// 
/// 
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封装

你可能感兴趣的:(.net,HttpClient)