当前位置: 首页 > article >正文

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


http://www.kler.cn/news/148924.html

相关文章:

  • 项目:基于UDP的网络聊天室
  • WordPress自动采集伪原创发布工具
  • Docker 概述与安装
  • 基于YOLO模型建筑工地个人防护设备目标检测
  • 只会在终端使用Python运行代码?这些高级用法了解了解
  • 基于Python+OpenCV+dlib+Tensorflow深度学习的人脸表情识别系统
  • 【数据库】聊聊一颗B+树 可以存储多少数据
  • SpringBoot+VUE3前后端分离-【支付宝支付】
  • k8s中pod的hostport端口突然无法访问故障处理
  • Scrum敏捷开发流程及支撑工具
  • 【深入解析git和gdb:版本控制与调试利器的终极指南】
  • Linux 基础-常用的命令和搭建 Java 部署环境
  • 使用vue脚手架创建vue项目
  • Linux 安装 Minio 配置 HTTPS
  • LangChain 14 SequencialChain链接不同的组件
  • 19 Go的时间日期
  • c 数组简介
  • 【c++|SDL】开始使用之---demo
  • Peter算法小课堂—高精度减法
  • <HarmonyOS第一课>从简单的页面开始 【课后考核】
  • nvm:node版本控制工具
  • 【Electron】上下键切换消息
  • 【Rust】快速教程——自定义类型、数字转枚举、Cargo运行
  • ArrayList与顺序表的简单理解
  • JSP forEach标签varStatus使用讲解(了解即可 基本用不到)
  • Day 12 周日和周一
  • 【LeetCode】挑战100天 Day12(热题+面试经典150题)
  • CSS逻辑组合伪类
  • ArrayList 和 HashMap 源码解析
  • MFC mysql 往数据库中写路径时,斜杠消失