156 lines
7.4 KiB
C#
Executable File
156 lines
7.4 KiB
C#
Executable File
using Opsoft.NetCore.O3App.Shared;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Opsoft.NetCore.O3App.Infrastructure
|
|
{
|
|
public abstract class HttpClientBase<TCategoryName> where TCategoryName : class
|
|
{
|
|
protected ILogger Logger { get; }
|
|
protected IHttpClientFactory HttpClientFactory { get; }
|
|
|
|
protected HttpClientBase(ILogger<TCategoryName> logger, IHttpClientFactory httpClientFactory)
|
|
{
|
|
Logger = Guard.ArgumentNotNull(logger, nameof(logger));
|
|
HttpClientFactory = Guard.ArgumentNotNull(httpClientFactory, nameof(httpClientFactory));
|
|
}
|
|
|
|
protected virtual string ContentType => Constants.ContentTypes.Json;
|
|
public bool WriteErrorLog { get; set; } = true;
|
|
|
|
#region async
|
|
public async Task<string> GetAsync(string url, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", string callerName = "")
|
|
{
|
|
Dictionary<string, dynamic> extraInfo = new Dictionary<string, dynamic>();
|
|
extraInfo.Add("url", url);
|
|
extraInfo.Add("method", "get");
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
string responseText = string.Empty;
|
|
|
|
try
|
|
{
|
|
var client = HttpClientFactory.CreateClient();
|
|
if (url.StartsWith(Constants.Protocols.HTTPS, StringComparison.CurrentCultureIgnoreCase))
|
|
{
|
|
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
|
|
}
|
|
if (timeout > 0)
|
|
{
|
|
client.Timeout = TimeSpan.FromMilliseconds(timeout);
|
|
}
|
|
if (headers?.Count > 0)
|
|
{
|
|
foreach (var item in headers)
|
|
{
|
|
client.DefaultRequestHeaders.Add(item.Key, item.Value);
|
|
}
|
|
}
|
|
var response = await client.GetAsync(url);
|
|
var resultBytes = response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync() : Array.Empty<byte>();
|
|
|
|
responseText = (encoding ?? Encoding.UTF8).GetString(resultBytes);
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("responseText", responseText);
|
|
Logger.Debug(extraInfo, filter1, filter2, callerName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (WriteErrorLog)
|
|
{
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("ex", ex);
|
|
Logger.Error(ex, extraInfo, filter1, filter2, callerName);
|
|
}
|
|
|
|
throw;
|
|
}
|
|
|
|
return responseText;
|
|
}
|
|
public async Task<T> GetAsync<T>(string url, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", [CallerMemberName]string callerName = "")
|
|
{
|
|
var response = await GetAsync(url, timeout, headers, encoding, filter1, filter2, callerName);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromJson<T>();
|
|
}
|
|
public async Task<string> PostAsync(string url, string postData, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", string callerName = "")
|
|
{
|
|
Dictionary<string, dynamic> extraInfo = new Dictionary<string, dynamic>();
|
|
extraInfo.Add("url", url);
|
|
extraInfo.Add("method", "post");
|
|
extraInfo.Add("requestText", postData);
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
string responseText = string.Empty;
|
|
try
|
|
{
|
|
var client = HttpClientFactory.CreateClient();
|
|
if (url.StartsWith(Constants.Protocols.HTTPS, StringComparison.CurrentCultureIgnoreCase))
|
|
{
|
|
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
|
|
}
|
|
if (timeout > 0)
|
|
{
|
|
client.Timeout = TimeSpan.FromMilliseconds(timeout);
|
|
}
|
|
var httpContent = new StringContent(postData);
|
|
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(ContentType);
|
|
if (headers?.Count > 0)
|
|
{
|
|
foreach (var item in headers)
|
|
{
|
|
client.DefaultRequestHeaders.Add(item.Key, item.Value);
|
|
}
|
|
}
|
|
|
|
var response = await client.PostAsync(url, httpContent);
|
|
var resultBytes = response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync() : Array.Empty<byte>();
|
|
|
|
responseText = (encoding ?? Encoding.UTF8).GetString(resultBytes);
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("responseText", responseText);
|
|
Logger.Debug(extraInfo, filter1, filter2, callerName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (WriteErrorLog)
|
|
{
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("ex", ex);
|
|
Logger.Error(ex, extraInfo, filter1, filter2, callerName);
|
|
}
|
|
|
|
throw;
|
|
}
|
|
|
|
return responseText;
|
|
}
|
|
public async Task<T> PostAsync<T>(string url, string postData, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", [CallerMemberName]string callerName = "")
|
|
{
|
|
var response = await PostAsync(url, postData, timeout, headers, encoding, filter1, filter2, callerName);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromJson<T>();
|
|
}
|
|
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn postData, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", [CallerMemberName]string callerName = "")
|
|
where TOut : class, new()
|
|
{
|
|
var response = await PostAsync(url, postData.ToJson(), timeout, headers, encoding, filter1, filter2, callerName);
|
|
return response.IsNullOrWhiteSpace() ? default(TOut) : response.FromJson<TOut>();
|
|
}
|
|
public async Task<T> PostWithXmlResponseAsync<T>(string url, string xmlString, int timeout = 6000, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", [CallerMemberName]string callerName = "")
|
|
where T : class, new()
|
|
{
|
|
var response = await PostAsync(url, xmlString, timeout, headers, encoding, filter1, filter2, callerName);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromXml<T>();
|
|
}
|
|
#endregion
|
|
}
|
|
}
|