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();
}
相关推荐
Prejudices2 分钟前
C++如何调用Python脚本
开发语言·c++·python
Daniel 大东3 分钟前
idea 解决缓存损坏问题
java·缓存·intellij-idea
wind瑞9 分钟前
IntelliJ IDEA插件开发-代码补全插件入门开发
java·ide·intellij-idea
HappyAcmen10 分钟前
IDEA部署AI代写插件
java·人工智能·intellij-idea
马剑威(威哥爱编程)15 分钟前
读写锁分离设计模式详解
java·设计模式·java-ee
我狠狠地刷刷刷刷刷15 分钟前
中文分词模拟器
开发语言·python·算法
鸽鸽程序猿16 分钟前
【算法】【优选算法】前缀和(上)
java·算法·前缀和
修道-032317 分钟前
【JAVA】二、设计模式之策略模式
java·设计模式·策略模式
wyh要好好学习19 分钟前
C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中
开发语言·c#·wpf
AitTech19 分钟前
C#实现:电脑系统信息的全面获取与监控
开发语言·c#