138 lines
3.9 KiB
C#
138 lines
3.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Json;
|
|
using System.Net.Security;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace Hua.DotNet.Code.Helper.Http;
|
|
|
|
public class HttpClientHelper : IHttpHelper
|
|
{
|
|
private readonly ILogger<HttpClientHelper> _logger;
|
|
|
|
public HttpClientHandler Handler { get; set; }
|
|
|
|
public Dictionary<string, string> Headers { get; set; }
|
|
|
|
public HttpClientHelper(ILogger<HttpClientHelper> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
public virtual HttpClient GetHttpClient()
|
|
{
|
|
HttpClient httpClient = ((Handler == null) ? new HttpClient() : new HttpClient(Handler));
|
|
if (Headers == null)
|
|
{
|
|
return httpClient;
|
|
}
|
|
foreach (KeyValuePair<string, string> header in Headers)
|
|
{
|
|
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
|
|
}
|
|
return httpClient;
|
|
}
|
|
|
|
public TOut? Get<TOut>(string url, int timeOut = 10)
|
|
{
|
|
return GetAsync<TOut>(url, timeOut).GetAwaiter().GetResult();
|
|
}
|
|
|
|
public TOut? Post<TIn, TOut>(string url, TIn input, int timeOut = 3)
|
|
{
|
|
try
|
|
{
|
|
HttpClient httpClient = GetHttpClient();
|
|
httpClient.Timeout = new TimeSpan(0, 0, timeOut);
|
|
_logger.LogInformation("Post:" + url + "\n[" + JsonConvert.SerializeObject((object)input) + "]");
|
|
HttpResponseMessage result = httpClient.PostAsync(url, JsonContent.Create(input)).GetAwaiter().GetResult();
|
|
string result2 = Task.FromResult(result.Content.ReadAsStringAsync()).Result.Result;
|
|
_logger.LogInformation(result2);
|
|
if (result.StatusCode != HttpStatusCode.OK)
|
|
{
|
|
_logger.LogError($"Error[{result.StatusCode}]:{url}\t{result2}");
|
|
}
|
|
return result.Content.ReadFromJsonAsync<TOut>().Result;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(url);
|
|
_logger.LogError(ex.Message);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
public async Task<TOut?> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 3) where TIn : class where TOut : class
|
|
{
|
|
_ = 2;
|
|
try
|
|
{
|
|
HttpClient httpClient = GetHttpClient();
|
|
httpClient.Timeout = new TimeSpan(0, 0, timeOut);
|
|
_logger.LogInformation("Post:" + url + "\n[" + JsonConvert.SerializeObject((object)input) + "]");
|
|
HttpResponseMessage result = await httpClient.PostAsync(url, JsonContent.Create(input));
|
|
string text = await result.Content.ReadAsStringAsync();
|
|
_logger.LogInformation(text);
|
|
if (result.StatusCode != HttpStatusCode.OK)
|
|
{
|
|
_logger.LogError($"Error[{result.StatusCode}]:{url}\t{text}");
|
|
}
|
|
return await result.Content.ReadFromJsonAsync<TOut>();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(url);
|
|
_logger.LogError(ex.Message);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
public async Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10)
|
|
{
|
|
_ = 2;
|
|
try
|
|
{
|
|
HttpClient httpClient = GetHttpClient();
|
|
httpClient.Timeout = new TimeSpan(0, 10, timeOut);
|
|
_logger.LogDebug("Get:" + url);
|
|
HttpResponseMessage result = await httpClient.GetAsync(url);
|
|
string arg = await result.Content.ReadAsStringAsync();
|
|
if (result.StatusCode != HttpStatusCode.OK)
|
|
{
|
|
_logger.LogDebug($"Error[{result.StatusCode}]:{url}\t{arg}");
|
|
}
|
|
return await result.Content.ReadFromJsonAsync<TOut>();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(url);
|
|
_logger.LogError(ex.Message);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
public bool DownloadFile(string url, string localPath)
|
|
{
|
|
ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;
|
|
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
|
|
Stream stream = new FileStream(localPath, FileMode.CreateNew);
|
|
try
|
|
{
|
|
Stream obj = (httpWebRequest?.GetResponse() as HttpWebResponse)?.GetResponseStream();
|
|
stream.Close();
|
|
obj?.Close();
|
|
return true;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|