.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);
作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
为之网-热爱软件编程 http://www.weizhi.cc/