zoukankan      html  css  js  c++  java
  • .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);
  • 相关阅读:
    2019沈阳网路赛 D. Fish eating fruit (点分治)
    2019南京网路赛 A.The beautiful values of the palace (主席树)
    洛谷 P2634 [国家集训队]聪聪可可(点分治)
    AcWing252 树 (点分治模板题)
    点分治模板 (洛谷 P3806)
    2020牛客寒假算法基础集训营2 J-求函数(线段树维护矩阵乘法)
    七夕祭(贪心+中位数)
    数据结构-集合
    数据结构-广义表
    数据结构-稀疏矩阵
  • 原文地址:https://www.cnblogs.com/puzi0315/p/15592298.html
Copyright © 2011-2022 走看看