.NetCore中HttpClient简单封装

HttpClient是经常用到的。我们做一个简单的封装类

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
public class HttpClientHelper
    {
        /// <summary>
        /// application/x-www-form-urlencoded
        /// </summary>
        /// <typeparam name="TBody"></typeparam>
        /// <param name="_client"></param>
        /// <param name="uri"></param>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public static async Task<TBody> PostFormAsync<TBody>(HttpClient _client, string uri, Dictionary<string, string> param)
        {

            try
            {
                using (var multipartFormDataContent = new FormUrlEncodedContent(param))
                {
                    Console.WriteLine(JsonConvert.SerializeObject(param));
                    var result = await _client.PostAsync(uri, multipartFormDataContent).Result.Content.ReadAsStringAsync();
                    var resp = JsonConvert.DeserializeObject<TBody>(result);
                    return resp;
                }
            }
            catch (Exception ex)
            {

                throw ex;

            }

        }



        /// <summary>
        /// application/json
        /// </summary>
        /// <typeparam name="TBody"></typeparam>
        /// <param name="_client"></param>
        /// <param name="uri"></param>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public static async Task<TBody> PostAsync<TBody>(HttpClient _client, string uri, dynamic requestData)
            => await SendAsync<TBody>(_client, "application/json", HttpMethod.Post, uri, requestData);

        public static async Task<TBody> GetAsync<TBody>(HttpClient _client, string uri, Dictionary<string, string> headerDict = null)
            => await SendAsync<TBody>(_client, "application/json", HttpMethod.Get, uri, null, headerDict);

        public static async Task<TBody> SendAsync<TBody>(HttpClient _client, string ContentType, HttpMethod method, string uri, dynamic requestData, Dictionary<string, string> headerDict=null)
        {
            string content = "";
            if (!string.IsNullOrEmpty(requestData))
            { 
                content = JsonConvert.SerializeObject(requestData, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
            }
            try
            {
                using (HttpRequestMessage message = new HttpRequestMessage(method, uri))
                {
                    if(headerDict != null)
                    {
                        foreach(var d in headerDict)
                        {
                            message.Headers.Add(d.Key, d.Value);
                        } 
                    }
                    using (HttpContent httpContent = new StringContent(content, Encoding.UTF8))
                    {
                        httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
                        message.Content = httpContent;

                        var httpResponseMessage = await _client.SendAsync(message);

                        string json = await httpResponseMessage.Content.ReadAsStringAsync();
                        var resp = JsonConvert.DeserializeObject<TBody>(json);

                        return resp;

                    }
                }
            }
            catch (Exception ex)
            {

                throw;

            }
        } 
    }

调用方法如下:

 var client = _clientFactory.CreateClient();

            string TenantAPI = "http://xxxx"; 

            var httpRet = await HttpClientHelper.GetAsync<Result<TenantInfoResp>>(client, TenantAPI);

 

posted @ 2021-11-23 11:05  沐雪架构师  阅读(1237)  评论(0编辑  收藏  举报