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();
}
相关推荐
cdut_suye4 分钟前
Linux工具使用指南:从apt管理、gcc编译到makefile构建与gdb调试
java·linux·运维·服务器·c++·人工智能·python
苹果醋316 分钟前
2020重新出发,MySql基础,MySql表数据操作
java·运维·spring boot·mysql·nginx
小蜗牛慢慢爬行17 分钟前
如何在 Spring Boot 微服务中设置和管理多个数据库
java·数据库·spring boot·后端·微服务·架构·hibernate
azhou的代码园20 分钟前
基于JAVA+SpringBoot+Vue的制造装备物联及生产管理ERP系统
java·spring boot·制造
波音彬要多做28 分钟前
41 stack类与queue类
开发语言·数据结构·c++·学习·算法
Swift社区36 分钟前
Excel 列名称转换问题 Swift 解答
开发语言·excel·swift
一道微光40 分钟前
Mac的M2芯片运行lightgbm报错,其他python包可用,x86_x64架构运行
开发语言·python·macos
矛取矛求1 小时前
QT的前景与互联网岗位发展
开发语言·qt
Leventure_轩先生1 小时前
[WASAPI]从Qt MultipleMedia来看WASAPI
开发语言·qt
向宇it1 小时前
【从零开始入门unity游戏开发之——unity篇01】unity6基础入门开篇——游戏引擎是什么、主流的游戏引擎、为什么选择Unity
开发语言·unity·c#·游戏引擎