.net HttpClient封装

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

相关推荐

  1. toggle封装

    2023-12-06 05:34:07       63 阅读
  2. 【C++】封装

    2023-12-06 05:34:07       43 阅读
  3. C# 封装

    2023-12-06 05:34:07       42 阅读
  4. 封装UUID

    2023-12-06 05:34:07       29 阅读
  5. axios封装、二次封装

    2023-12-06 05:34:07       72 阅读
  6. C#面向对象——封装封装案例示例

    2023-12-06 05:34:07       44 阅读
  7. .net HttpClient封装

    2023-12-06 05:34:07       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 05:34:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 05:34:07       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 05:34:07       87 阅读
  4. Python语言-面向对象

    2023-12-06 05:34:07       96 阅读

热门阅读

  1. 计算机网络中速率和带宽的区别

    2023-12-06 05:34:07       55 阅读
  2. go使用aes加密算法

    2023-12-06 05:34:07       50 阅读
  3. pytorch学习9-优化器学习

    2023-12-06 05:34:07       62 阅读
  4. Zookeeper

    2023-12-06 05:34:07       59 阅读
  5. 回顾Django的第六天

    2023-12-06 05:34:07       46 阅读
  6. Golang rsa 验证

    2023-12-06 05:34:07       60 阅读