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.Common
{
///
/// HTTP帮助类
///
public class HttpHelperAsync
{
private IHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
public HttpHelperAsync(IHttpClientFactory httpClientFactory, ILogger logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
#region 异步
///
/// 发起POST异步请求表单
///
/// 请求地址
/// POST提交的内容
/// POST内容的媒体类型,如:application/xml、application/json
/// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回string
public async Task PostFormAsync(string url, MultipartFormDataContent content,
Dictionary 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}";
}
}
///
/// 发起GET异步请求
///
/// 返回类型
/// 请求地址
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回string
public async Task GetAsync(string url, Dictionary 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;
}
}
}
}
///
/// 发起POST异步请求
///
/// 请求地址
/// POST提交的内容
/// POST内容的媒体类型,如:application/xml、application/json
/// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回string
public async Task PostAsync(string url, string body,
Dictionary 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}";
}
}
///
/// 发起POST异步请求
///
/// 请求地址
/// POST提交的内容
/// POST内容的媒体类型,如:application/xml、application/json
/// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回string
public async Task PutAsync(string url, string body,
string bodyMediaType = null,
string responseContentType = null,
Dictionary 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;
}
}
}
}
///
/// 发起GET异步请求
///
/// 返回类型
/// 请求地址
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回string
public async Task DeleteAsync(string url, Dictionary 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;
}
}
}
}
///
/// 发起GET异步请求
///
/// 返回类型
/// 请求地址
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回T
public async Task GetAsync(string url, Dictionary headers = null, int timeOut = 30) where T : new()
{
string responseString = await GetAsync(url, headers, timeOut);
if (!string.IsNullOrWhiteSpace(responseString))
{
return JsonConvert.DeserializeObject(responseString);
}
else
{
return default(T);
}
}
///
/// 发起POST异步请求
///
/// 返回类型
/// 请求地址
/// POST提交的内容
/// POST内容的媒体类型,如:application/xml、application/json
/// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回T
public async Task PostAsync(string url, string body,
Dictionary 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(responseString);
}
else
{
return default(T);
}
}
///
/// 发起PUT异步请求
///
/// 返回类型
/// 请求地址
/// POST提交的内容
/// POST内容的媒体类型,如:application/xml、application/json
/// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回T
public async Task PutAsync(string url, string body,
string bodyMediaType = null,
string responseContentType = null,
Dictionary 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(responseString);
}
else
{
return default(T);
}
}
///
/// 发起DELETE异步请求
///
/// 返回类型
/// 请求地址
/// 请求头信息
/// 请求超时时间,单位秒
/// 返回T
public async Task DeleteAsync(string url, Dictionary headers = null, int timeOut = 30) where T : new()
{
string responseString = await DeleteAsync(url, headers, timeOut);
if (!string.IsNullOrWhiteSpace(responseString))
{
return JsonConvert.DeserializeObject(responseString);
}
else
{
return default(T);
}
}
#region 私有函数
///
/// 获取请求的主机名
///
///
///
private static string GetHostName(string url)
{
if (!string.IsNullOrWhiteSpace(url))
{
return url.Replace("https://", "").Replace("http://", "").Split('/')[0];
}
else
{
return "AnyHost";
}
}
#endregion
#endregion
#region 同步
///
/// 发起GET同步请求
///
///
///
///
///
///
public string HttpGet(string url, Dictionary 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 "";
}
///
/// 发起POST同步请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public string HttpPost(string url, string postData = null, Dictionary 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
}
}