C# HttpClient Get Post简单封装

文章目录

  • 前言
  • 封装好的代码
  • 测试接口
  • 测试代码

前言

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

封装好的代码

 public class MyHttpHelper
 {

     private string baseUrl;
     

     /// 
     /// 基础Api
     /// 
     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;
     }

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


     /// 
     /// 序列化返回值
     /// 
     /// 
     /// 
     /// 
     /// 
     /// 
     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>();
     }

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

     /// 
     /// 自定义的转发功能
     /// 
     /// 
     /// 
     /// 
     /// 
     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"));
     }

     /// 
     /// 字典转参数
     /// 
     /// 
     /// 
     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上面发布后端接口

C# HttpClient Get Post简单封装_第1张图片

实体类

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
  /// 
  /// 测试类
  /// 
  [Route("api/[controller]/[action]")]
  [ApiController]
  public class TestController : ControllerBase
  {

      /// 
      /// 测试Num
      /// 
      /// 
      /// 
      [HttpGet]
      public int TestNum(int num)
      {

          return num;
      }

      /// 
      /// 测试Post
      /// 
      /// 
      /// 
      [HttpPost]
      public Person TestPerson(Person person)
      {
          return person;
      }


      /// 
      /// Person+Num
      /// 
      /// 
      /// 
      /// 
      [HttpPost]
      public Person TestPersonNum(int num,Person person)
      {
          person.Id += num;
          return person;

      }
      
  }

测试代码

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();
}

C# HttpClient Get Post简单封装_第2张图片

你可能感兴趣的:(C#,c#,java,开发语言)