using Newtonsoft.Json;
/// <summary>
/// Http 请求工具
/// </summary>
public class HttpClientUtils
{
/// <summary&gt;
/// 请求域名
/// </summary&gt;
public static string BaseUrl { get; set; } = "http://localhost:5016";
/// <summary&gt;
/// 发送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封装

原文地址:https://blog.csdn.net/qq_41942413/article/details/134680561

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_35558.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注