C# HttpClient Get Post简单封装

文章目录

前言

微软官方有Get和Post请求,我把他简单化处理一下

封装好的代码

csharp 复制代码
 public class MyHttpHelper
 {

     private string baseUrl;
     

     /// <summary>
     /// 基础Api
     /// </summary>
     public string BaseUrl
     {
         get
         {
             return baseUrl;
         }

         set
         {
             baseUrl = value;
             MyHttpClient = new HttpClient()
             {
                 BaseAddress = new Uri(baseUrl)
             };
         }
     }


     public HttpClient MyHttpClient { get; set; }
     public MyHttpHelper()
     {

     }

     public MyHttpHelper(string baseUrl)
     {
         BaseUrl = baseUrl;
     }

     /// <summary>
     /// 序列化返回值
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="api"></param>
     /// <param name="strParams"></param>
     /// <returns></returns>
     public async Task<T> JsonHttpGet<T>(string api, Dictionary<string, string> strParams)
     {
         var res = await MyHttpGet(api, strParams);
         return await res.Content.ReadFromJsonAsync<T>();
     }


     /// <summary>
     /// 序列化返回值
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="api"></param>
     /// <param name="value"></param>
     /// <param name="strParams"></param>
     /// <returns></returns>
     public async Task<T> JsonHttpPost<T>(string api, object value, Dictionary<string, string> strParams)
     {
         var res = await MyHttpPost(api, value, strParams);
         return await res.Content.ReadFromJsonAsync<T>();
     }

     /// <summary>
     /// 序列化请求
     /// </summary>
     /// <param name="api"></param>
     /// <param name="param"></param>
     /// <returns></returns>
     public async Task<HttpResponseMessage> MyHttpGet(string api, Dictionary<string, string> param)
     {
         string paramStr = DictionaryToParams(param);
         return await MyHttpClient.GetAsync(api + paramStr);
     }

     /// <summary>
     /// 自定义的转发功能
     /// </summary>
     /// <param name="api"></param>
     /// <param name="dataname"></param>
     /// <param name="value"></param>
     /// <returns></returns>
     public Task<HttpResponseMessage> MyHttpPost(string api, object value, Dictionary<string, string> strParams)
     {
         return MyHttpClient.PostAsync(api + DictionaryToParams(strParams), new StringContent(JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json"));
     }

     /// <summary>
     /// 字典转参数
     /// </summary>
     /// <param name="param"></param>
     /// <returns></returns>
     public string DictionaryToParams(Dictionary<string, string> param)
     {
         var res = "";
         if (param != null)
         {
             var list = param.ToList();
             if(list.Count != 0)
             {
                 for (var i = 0; i < list.Count; i++)
                 {

                     if (i != 0)
                     {
                         res += "&";
                     }
                     res += $"{list[i].Key}={list[i].Value}";
                 }
                 res = "?" + res;
             }
           
         }
         return res;
     }
 }

测试接口

不懂的可以自己去看一下我的这篇文章

.NET Core webapi 从零开始在IIS上面发布后端接口

实体类

csharp 复制代码
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
csharp 复制代码
  /// <summary>
  /// 测试类
  /// </summary>
  [Route("api/[controller]/[action]")]
  [ApiController]
  public class TestController : ControllerBase
  {

      /// <summary>
      /// 测试Num
      /// </summary>
      /// <param name="num"></param>
      /// <returns></returns>
      [HttpGet]
      public int TestNum(int num)
      {

          return num;
      }

      /// <summary>
      /// 测试Post
      /// </summary>
      /// <param name="num"></param>
      /// <returns></returns>
      [HttpPost]
      public Person TestPerson(Person person)
      {
          return person;
      }


      /// <summary>
      /// Person+Num
      /// </summary>
      /// <param name="num"></param>
      /// <param name="person"></param>
      /// <returns></returns>
      [HttpPost]
      public Person TestPersonNum(int num,Person person)
      {
          person.Id += num;
          return person;

      }
      
  }

测试代码

csharp 复制代码
static void Main(string[] args)
{
    var httpHelper = new MyHttpHelper("https://localhost:7291/");
    Task.Run(async() =>
    {
        var res = await httpHelper.JsonHttpGet<int>("/api/Test/TestNum", new Dictionary<string, string> { { "num", "7" } });
        Console.WriteLine(res);
        var res2 = await httpHelper.JsonHttpPost<Person>("/api/Test/TestPerson", new Person() { Id = 4, Name = "小王" }, null);
        Console.WriteLine(JsonConvert.SerializeObject(res2));

        var res3 = await httpHelper.JsonHttpPost<Person>("/api/Test/TestPersonNum", new Person() { Id = 4, Name = "小王" }, new Dictionary<string, string>() { { "Num", "4" } });

        Console.WriteLine(JsonConvert.SerializeObject(res3));

    });
   


    Console.WriteLine("Hello, World!");

    Console.ReadKey();
}
相关推荐
qq_45973003几秒前
C 语言面向对象
c语言·开发语言
佚先森8 分钟前
2024ARM网络验证 支持一键云注入引流弹窗注册机 一键脱壳APP加固搭建程序源码及教程
java·html
菜鸟学Python9 分钟前
Python 数据分析核心库大全!
开发语言·python·数据挖掘·数据分析
一个小坑货16 分钟前
Cargo Rust 的包管理器
开发语言·后端·rust
bluebonnet2721 分钟前
【Rust练习】22.HashMap
开发语言·后端·rust
古月居GYH21 分钟前
在C++上实现反射用法
java·开发语言·c++
吾与谁归in39 分钟前
【C#设计模式(13)——代理模式(Proxy Pattern)】
设计模式·c#·代理模式
吾与谁归in40 分钟前
【C#设计模式(14)——责任链模式( Chain-of-responsibility Pattern)】
设计模式·c#·责任链模式
在下不上天1 小时前
Flume日志采集系统的部署,实现flume负载均衡,flume故障恢复
大数据·开发语言·python