1、在Startup里面注册IHttpClientFactory
//注册IHttpClientFactory
services.AddHttpClient();
//注册IHttpClientFactory的实现到DI容器
services.AddTransient<HttpClientHelper>();
2、HttpClientHelper代码,包含Get,POST,PUT,Delete请求。
/// <summary>
/// HTTP帮助类
/// </summary>
public class HttpClientHelper
{
private IHttpClientFactory _httpClientFactory;
public HttpClientHelper(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
/// <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,
string bodyMediaType = "application/json",
string responseContentType = "application/json",
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.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
else
{
return string.Empty;
}
}
}
}
/// <summary>
/// 发起Put异步请求
/// </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,
Dictionary<string, string> headers = null,
string bodyMediaType = null,
string responseContentType = 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,
string bodyMediaType = null,
string responseContentType = null,
Dictionary<string, string> headers = null,
int timeOut = 30) where T : new()
{
string responseString = await PostAsync(url, body, headers, bodyMediaType, responseContentType, timeOut);
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, headers, bodyMediaType, responseContentType, 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
}