231 lines
10 KiB
C#
231 lines
10 KiB
C#
using Microsoft.Extensions.Logging;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Net.Http;
|
||
using System.Net.Http.Headers;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading.Tasks;
|
||
using WMS.Web.Core.Exceptions;
|
||
using WMS.Web.Domain.IService.Public;
|
||
|
||
namespace WMS.Web.Domain.Services.Public
|
||
{
|
||
public class HttpClientService : IHttpClientService
|
||
{
|
||
private readonly IHttpClientFactory _clientFactory;
|
||
private readonly ILogger<HttpClientService> _logger;
|
||
private Dictionary<string, string> headers;
|
||
private Dictionary<string, string> contentHeaders;
|
||
public HttpClientService(IHttpClientFactory clientFactory, ILogger<HttpClientService> logger)
|
||
{
|
||
_clientFactory = clientFactory;
|
||
_logger = logger;
|
||
headers = new Dictionary<string, string>();
|
||
headers.Add("Accept", "application/json");
|
||
headers.Add("User-Agent", "HttpClientFactory-Sample");
|
||
|
||
contentHeaders = new Dictionary<string, string>();
|
||
contentHeaders.Add("Content-Type", "application/json; charset=utf-8");
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// Get方法
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public async Task<T> GetAsync<T>(string url, int timeoutSecond = 180)
|
||
{
|
||
try
|
||
{
|
||
var client = BuildHttpClient(headers, timeoutSecond);
|
||
var response = await client.GetAsync(url);
|
||
//var responseContent = await response.Content.ReadAsStreamAsync();//1.相比ReadAsString这个方法返回要快点,效率高
|
||
var responseContent = await response.Content.ReadAsStringAsync(); //2.当前使用这里是为了迎合错误信息观看
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var t = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||
//var t = await JsonSerializer.DeserializeAsync<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });//3.配合1的ReadAsStream使用
|
||
return t;
|
||
}
|
||
|
||
throw new WebHttpException(response.StatusCode.ToString(), "请求出错");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError($"HttpGet:{url} Error:{ex.Message}");
|
||
throw new Exception($"HttpGet:{url} Error", ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Get方法
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public async Task<T> GetAsync<T>(string url, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
|
||
{
|
||
try
|
||
{
|
||
var client = BuildHttpClient(dicHeaders, timeoutSecond);
|
||
var response = await client.GetAsync(url);
|
||
//var responseContent = await response.Content.ReadAsStreamAsync();//1.相比ReadAsString这个方法返回要快点,效率高
|
||
var responseContent = await response.Content.ReadAsStringAsync(); //2.当前使用这里是为了迎合错误信息观看
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var t = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||
//var t = await JsonSerializer.DeserializeAsync<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });//3.配合1的ReadAsStream使用
|
||
return t;
|
||
}
|
||
|
||
throw new WebHttpException(response.StatusCode.ToString(), "请求出错");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError($"HttpGet:{url} Error:{ex.Message}");
|
||
throw new Exception($"HttpGet:{url} Error", ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Post方法
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="requestBody"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public async Task<T> PostAsync<T>(string url, string requestBody, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
|
||
{
|
||
var client = BuildHttpClient(dicHeaders, timeoutSecond);
|
||
var requestContent = GenerateStringContent(requestBody, contentHeaders);
|
||
var response = await client.PostAsync(url, requestContent);
|
||
var responseContent = await response.Content.ReadAsStringAsync();
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var t = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||
return t;
|
||
}
|
||
|
||
_logger.LogError($"HttpGet:{url} Error:{responseContent}");
|
||
throw new WebHttpException(response.StatusCode.ToString(), responseContent);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Post方法
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="requestBody"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public async Task<T> PostAsync<T>(string url, string requestBody, int timeoutSecond = 180)
|
||
{
|
||
var client = BuildHttpClient(null, timeoutSecond);
|
||
var requestContent = GenerateStringContent(requestBody, contentHeaders);
|
||
var response = await client.PostAsync(url, requestContent);
|
||
var responseContent = await response.Content.ReadAsStringAsync();
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var t = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||
if (t == null)
|
||
_logger.LogInformation($"获取单点数据为空---{responseContent}");
|
||
return t;
|
||
}
|
||
|
||
_logger.LogError($"HttpGet:{url} Error:{responseContent}");
|
||
throw new WebHttpException(response.StatusCode.ToString(), responseContent);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 公共http请求
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="method"></param>
|
||
/// <param name="requestBody"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public async Task<T> ExecuteAsync<T>(string url, HttpMethod method, string requestBody, Dictionary<string, string> dicHeaders, int timeoutSecond = 180)
|
||
{
|
||
var client = BuildHttpClient(null, timeoutSecond);
|
||
var request = GenerateHttpRequestMessage(url, requestBody, method, dicHeaders);
|
||
var response = await client.SendAsync(request);
|
||
var responseContent = await response.Content.ReadAsStringAsync();
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var t = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||
|
||
return t;
|
||
}
|
||
|
||
throw new WebHttpException(response.StatusCode.ToString(), responseContent);
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 设置HttpRequestMessage
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="requestBody"></param>
|
||
/// <param name="method"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <returns></returns>
|
||
private HttpRequestMessage GenerateHttpRequestMessage(string url, string requestBody, HttpMethod method, Dictionary<string, string> dicHeaders)
|
||
{
|
||
var request = new HttpRequestMessage(method, url);
|
||
if (!string.IsNullOrEmpty(requestBody)) request.Content = new StringContent(requestBody);
|
||
if (dicHeaders != null)
|
||
foreach (var headerItme in dicHeaders)
|
||
request.Headers.Add(headerItme.Key, headerItme.Value);
|
||
return request;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置请求内容
|
||
/// </summary>
|
||
/// <param name="requestBody"></param>
|
||
/// <param name="dicHeaders"></param>
|
||
/// <returns></returns>
|
||
private StringContent GenerateStringContent(string requestBody, Dictionary<string, string> dicHeaders)
|
||
{
|
||
var content = new StringContent(requestBody);
|
||
if (dicHeaders != null)
|
||
content.Headers.Remove("content-type");
|
||
foreach (var headerItme in dicHeaders)
|
||
content.Headers.Add(headerItme.Key, headerItme.Value);
|
||
return content;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 设置请求头和超时时间:返回client
|
||
/// </summary>
|
||
/// <param name="dicDefaultHeaders"></param>
|
||
/// <param name="timeoutSecond"></param>
|
||
/// <returns></returns>
|
||
public HttpClient BuildHttpClient(Dictionary<string, string> dicDefaultHeaders, int? timeoutSecond=180)
|
||
{
|
||
var httpClient = _clientFactory.CreateClient("ops_client");
|
||
httpClient.DefaultRequestHeaders.Clear(); //为了使客户端不受最后一个请求的影响,它需要清除DefaultRequestHeaders
|
||
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||
if (dicDefaultHeaders != null)
|
||
foreach (var headItem in dicDefaultHeaders)
|
||
if (!httpClient.DefaultRequestHeaders.Contains(headItem.Key))
|
||
httpClient.DefaultRequestHeaders.Add(headItem.Key, headItem.Value);
|
||
|
||
if (timeoutSecond != null) httpClient.Timeout = TimeSpan.FromSeconds(timeoutSecond.Value);
|
||
return httpClient;
|
||
}
|
||
}
|
||
}
|