|
- using Microsoft.Extensions.Logging;
- 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;
-
- namespace TelpoPush.WanJiaAn.Worker.Common
- {
- /// <summary>
- /// HTTP帮助类
- /// </summary>
- public class HttpHelperAsync
- {
- private IHttpClientFactory _httpClientFactory;
- private readonly ILogger<HttpHelperAsync> _logger;
- public HttpHelperAsync(IHttpClientFactory httpClientFactory, ILogger<HttpHelperAsync> logger)
- {
- _httpClientFactory = httpClientFactory;
- _logger = logger;
- }
-
-
- #region 异步
- /// <summary>
- /// 发起POST异步请求表单
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="body">POST提交的内容</param>
- /// <param name="bodyMediaType">POST内容的媒体类型,如:application/xml、application/json</param>
- /// <param name="responseContentType">HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回string</returns>
- public async Task<string> PostFormAsync(string url, MultipartFormDataContent content,
- Dictionary<string, string> headers = null,
- int timeOut = 5)
- {
- try
- {
- var hostName = GetHostName(url);
- using (HttpClient client = _httpClientFactory.CreateClient(hostName))
- {
- client.Timeout = TimeSpan.FromSeconds(timeOut);
- if (headers?.Count > 0)
- {
- foreach (string key in headers.Keys)
- {
- client.DefaultRequestHeaders.Add(key, headers[key]);
- }
- }
- content.Headers.Add("ContentType", "multipart/form-data");//声明头部
- using (HttpResponseMessage response = await client.PostAsync(url, content))
- {
- return JsonConvert.SerializeObject(new { response.IsSuccessStatusCode, response.StatusCode });
- //if (response.IsSuccessStatusCode)
- //{
- // string responseString = await response.Content.ReadAsStringAsync();
- // return responseString;
- //}
- //else
- //{
- // return string.Empty;
- //}
- }
- }
- }
- catch (Exception ex)
- {
- return $"推送完成:请求响应超过{timeOut}秒,异常 {ex.Message}";
- }
- }
-
-
-
- /// <summary>
- /// 发起GET异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回string</returns>
- public async Task<string> GetAsync(string url, Dictionary<string, string> headers = null, int timeOut = 30)
- {
- var hostName = GetHostName(url);
- using (HttpClient client = _httpClientFactory.CreateClient(hostName))
- {
- client.Timeout = TimeSpan.FromSeconds(timeOut);
- if (headers?.Count > 0)
- {
- foreach (string key in headers.Keys)
- {
- client.DefaultRequestHeaders.Add(key, headers[key]);
- }
- }
- using (HttpResponseMessage response = await client.GetAsync(url))
- {
- if (response.IsSuccessStatusCode)
- {
- string responseString = await response.Content.ReadAsStringAsync();
- return responseString;
- }
- else
- {
- return string.Empty;
- }
- }
- }
- }
-
-
- /// <summary>
- /// 发起POST异步请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="body">POST提交的内容</param>
- /// <param name="bodyMediaType">POST内容的媒体类型,如:application/xml、application/json</param>
- /// <param name="responseContentType">HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回string</returns>
- public async Task<string> PostAsync(string url, string body,
- Dictionary<string, string> headers = null,
- int timeOut = 30,
- string bodyMediaType = "application/json",
- string responseContentType = "application/json;charset=utf-8")
- {
-
- //content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
-
- //var clientHandler = new HttpClientHandler
- //{
- // ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
- //};
- //using (var client = new HttpClient(clientHandler))
- //{
- // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
- try
- {
- var hostName = GetHostName(url);
- using (HttpClient client = _httpClientFactory.CreateClient(hostName))
- {
- client.Timeout = TimeSpan.FromSeconds(timeOut);
- if (headers?.Count > 0)
- {
- foreach (string key in headers.Keys)
- {
- client.DefaultRequestHeaders.Add(key, headers[key]);
- }
- }
- StringContent content = new StringContent(body, System.Text.Encoding.UTF8, mediaType: bodyMediaType);
- if (!string.IsNullOrWhiteSpace(responseContentType))
- {
- content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(responseContentType);
- }
- using (HttpResponseMessage response = await client.PostAsync(url, content))
- {
- if (response.IsSuccessStatusCode)
- {
- string responseString = await response.Content.ReadAsStringAsync();
- return responseString;
- }
- else
- return $"请求异常:{response.IsSuccessStatusCode},{response.StatusCode}";
- }
- }
- }
- catch(Exception ex)
- {
- return $"请求异常:{ex.Message}";
- }
- }
-
- /// <summary>
- /// 发起POST异步请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="body">POST提交的内容</param>
- /// <param name="bodyMediaType">POST内容的媒体类型,如:application/xml、application/json</param>
- /// <param name="responseContentType">HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回string</returns>
- public async Task<string> PutAsync(string url, string body,
- string bodyMediaType = null,
- string responseContentType = null,
- Dictionary<string, string> headers = null,
- int timeOut = 30)
- {
- var hostName = GetHostName(url);
- using (HttpClient client = _httpClientFactory.CreateClient(hostName))
- {
- client.Timeout = TimeSpan.FromSeconds(timeOut);
- if (headers?.Count > 0)
- {
- foreach (string key in headers.Keys)
- {
- client.DefaultRequestHeaders.Add(key, headers[key]);
- }
- }
- StringContent content = new StringContent(body, System.Text.Encoding.UTF8, mediaType: bodyMediaType);
- if (!string.IsNullOrWhiteSpace(responseContentType))
- {
- content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(responseContentType);
- }
- using (HttpResponseMessage response = await client.PutAsync(url, content))
- {
- if (response.IsSuccessStatusCode)
- {
- string responseString = await response.Content.ReadAsStringAsync();
- return responseString;
- }
- else
- {
- return string.Empty;
- }
- }
- }
- }
-
- /// <summary>
- /// 发起GET异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回string</returns>
- public async Task<string> DeleteAsync(string url, Dictionary<string, string> headers = null, int timeOut = 30)
- {
- var hostName = GetHostName(url);
- using (HttpClient client = _httpClientFactory.CreateClient(hostName))
- {
- client.Timeout = TimeSpan.FromSeconds(timeOut);
- if (headers?.Count > 0)
- {
- foreach (string key in headers.Keys)
- {
- client.DefaultRequestHeaders.Add(key, headers[key]);
- }
- }
- using (HttpResponseMessage response = await client.DeleteAsync(url))
- {
- if (response.IsSuccessStatusCode)
- {
- string responseString = await response.Content.ReadAsStringAsync();
- return responseString;
- }
- else
- {
- return string.Empty;
- }
- }
- }
- }
-
- /// <summary>
- /// 发起GET异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回T</returns>
- public async Task<T> GetAsync<T>(string url, Dictionary<string, string> headers = null, int timeOut = 30) where T : new()
- {
- string responseString = await GetAsync(url, headers, timeOut);
- if (!string.IsNullOrWhiteSpace(responseString))
- {
- return JsonConvert.DeserializeObject<T>(responseString);
- }
- else
- {
- return default(T);
- }
- }
-
-
- /// <summary>
- /// 发起POST异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="body">POST提交的内容</param>
- /// <param name="bodyMediaType">POST内容的媒体类型,如:application/xml、application/json</param>
- /// <param name="responseContentType">HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回T</returns>
- public async Task<T> PostAsync<T>(string url, string body,
- Dictionary<string, string> headers = null,
- int timeOut = 30,
- string bodyMediaType = "application/json",
- string responseContentType = "application/json;charset=utf-8"
- ) where T : new()
- {
- string responseString = await PostAsync(url, body, headers, timeOut, bodyMediaType, responseContentType);
- if (!string.IsNullOrWhiteSpace(responseString))
- {
- return JsonConvert.DeserializeObject<T>(responseString);
- }
- else
- {
- return default(T);
- }
- }
-
- /// <summary>
- /// 发起PUT异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="body">POST提交的内容</param>
- /// <param name="bodyMediaType">POST内容的媒体类型,如:application/xml、application/json</param>
- /// <param name="responseContentType">HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回T</returns>
- public async Task<T> PutAsync<T>(string url, string body,
- string bodyMediaType = null,
- string responseContentType = null,
- Dictionary<string, string> headers = null,
- int timeOut = 30) where T : new()
- {
- string responseString = await PutAsync(url, body, bodyMediaType, responseContentType, headers, timeOut);
- if (!string.IsNullOrWhiteSpace(responseString))
- {
- return JsonConvert.DeserializeObject<T>(responseString);
- }
- else
- {
- return default(T);
- }
- }
-
- /// <summary>
- /// 发起DELETE异步请求
- /// </summary>
- /// <typeparam name="T">返回类型</typeparam>
- /// <param name="url">请求地址</param>
- /// <param name="headers">请求头信息</param>
- /// <param name="timeOut">请求超时时间,单位秒</param>
- /// <returns>返回T</returns>
- public async Task<T> DeleteAsync<T>(string url, Dictionary<string, string> headers = null, int timeOut = 30) where T : new()
- {
- string responseString = await DeleteAsync(url, headers, timeOut);
- if (!string.IsNullOrWhiteSpace(responseString))
- {
- return JsonConvert.DeserializeObject<T>(responseString);
- }
- else
- {
- return default(T);
- }
- }
- #region 私有函数
-
- /// <summary>
- /// 获取请求的主机名
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- private static string GetHostName(string url)
- {
- if (!string.IsNullOrWhiteSpace(url))
- {
- return url.Replace("https://", "").Replace("http://", "").Split('/')[0];
- }
- else
- {
- return "AnyHost";
- }
- }
-
- #endregion
-
-
- #endregion
-
- #region 同步
-
- /// <summary>
- /// 发起GET同步请求
- /// </summary>
- /// <param name="url"></param>
- /// <param name="headers"></param>
- /// <param name="contentType"></param>
- /// <returns></returns>
- ///
-
-
- public string HttpGet(string url, Dictionary<string, string> headers = null, string contentType = "application/json;charset=utf-8")
- {
- if (string.IsNullOrEmpty(url)) return "";
- try
- {
- using (HttpClient client = new HttpClient())
- {
- if (contentType != null)
- client.DefaultRequestHeaders.Add("ContentType", contentType);
- if (headers != null)
- {
- foreach (var header in headers)
- client.DefaultRequestHeaders.Add(header.Key, header.Value);
- }
- HttpResponseMessage response = client.GetAsync(url).Result;
- return response.Content.ReadAsStringAsync().Result;
- }
- }
- catch (Exception ex)
- {
- _logger.LogDebug($"HttpGet/URL:{url},headers:{JsonConvert.SerializeObject(headers)},异常:{ex.Message}|{ex.Source}|{ex.StackTrace}");
- }
- return "";
- }
- /// <summary>
- /// 发起POST同步请求
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
- /// <param name="headers">填充消息头</param>
- /// <returns></returns>
- public string HttpPost(string url, string postData = null, Dictionary<string, string> headers = null, string contentType = "application/json")
- {
- if (string.IsNullOrEmpty(url)) return "";
- try
- {
- postData = postData ?? "";
- using (HttpClient client = new HttpClient())
- {
- if (headers != null)
- {
- foreach (var header in headers)
- client.DefaultRequestHeaders.Add(header.Key, header.Value);
- }
- using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
- {
- if (contentType != null)
- httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
-
- HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
- return response.Content.ReadAsStringAsync().Result;
- }
- }
- }
- catch (Exception ex){
- _logger.LogDebug($"HttpPost/URL:{url},postStr:{postData},headers:{JsonConvert.SerializeObject(headers)},异常:{ex.Message}|{ex.Source}|{ex.StackTrace}");
- }
- return "";
- }
-
-
- #endregion
- }
- }
|