78 lines
2.0 KiB
C#
78 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using RestSharp;
|
|
|
|
namespace Hua.DotNet.Code.Helper.Http;
|
|
|
|
public class RestClientHttpHelper : IHttpHelper
|
|
{
|
|
private ILogger<RestClientHttpHelper> _logger;
|
|
|
|
public HttpClientHandler Handler { get; set; }
|
|
|
|
public Dictionary<string, string> Headers { get; set; }
|
|
|
|
public RestClientHttpHelper(ILogger<RestClientHttpHelper> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
protected virtual RestClient GetHttpClient()
|
|
{
|
|
var val = ((Handler == null) ? new RestClient() : new RestClient((HttpMessageHandler)Handler, true));
|
|
if (Headers == null)
|
|
{
|
|
return val;
|
|
}
|
|
foreach (KeyValuePair<string, string> header in Headers)
|
|
{
|
|
val.AddDefaultHeader(header.Key, header.Value);
|
|
}
|
|
return val;
|
|
}
|
|
|
|
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10, CancellationToken? cts = null) where TIn : class where TOut : class
|
|
{
|
|
try
|
|
{
|
|
var client = GetHttpClient();
|
|
var request = new RestRequest(url, Method.Post).AddJsonBody<TIn>(input, "application/json");
|
|
request.Timeout = TimeSpan.FromSeconds(timeOut);
|
|
await client.PostAsync(request, cts ?? CancellationToken.None);
|
|
return await client.PostAsync<TOut>(request, cts??CancellationToken.None);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(url);
|
|
_logger.LogError(ex.Message);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
public async Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10, CancellationToken? cts = null)
|
|
{
|
|
try
|
|
{
|
|
using RestClient httpClient = GetHttpClient();
|
|
var val = new RestRequest(url,Method.Get);
|
|
return await httpClient.GetAsync<TOut>(val, cts ?? CancellationToken.None);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(url);
|
|
_logger.LogError(ex.Message);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
|
|
public bool DownloadFile(string url, string fileFullName)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
}
|