Files
2026-10-12 16:22:04 +08:00

202 lines
6.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Common.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace Common.Request
{
public class RequestApi : IRequestApi
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ILogger<RequestApi> _logger;
private Dictionary<string, string> defaultHeader = null;
public RequestApi(IHttpContextAccessor httpContextAccessor, ILogger<RequestApi> logger)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
defaultHeader = new Dictionary<string, string>();
if (_httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request != null &&
_httpContextAccessor.HttpContext.Request.Headers != null)
{
defaultHeader.Add("token", _httpContextAccessor.HttpContext.Request.Headers["token"].ToString() ?? "");
}
}
public async Task<string> GetAsync(string host, string resource, Dictionary<string, object> param = null,
Dictionary<string, string> headers = null, int timeOut = 5)
{
var options = new RestClientOptions(host)
{
ThrowOnAnyError = true
};
var restClient = new RestClient(options);
var request = new RestRequest(resource)
{
Timeout = TimeSpan.FromSeconds(timeOut)
};
if (param != null && param.Count > 0)
{
foreach (var item in param.Where(e => e.Value != null))
{
request.AddQueryParameter(item.Key, item.Value.ToString());
}
}
if (headers != null)
{
defaultHeader = headers;
}
request.AddHeaders(defaultHeader);
var restResponse = await restClient.ExecuteGetAsync(request);
return HandleResponse(restResponse, resource, param);
}
public async Task<string> PostAsync(string host, string resource, object param,
Dictionary<string, string> queryParams = null, Dictionary<string, string> headers = null, int timeOut = 5)
{
var options = new RestClientOptions(host)
{
ThrowOnAnyError = true
};
var restClient = new RestClient(options);
var request = new RestRequest(resource)
{
Timeout = TimeSpan.FromSeconds(timeOut)
};
if (queryParams != null && queryParams.Count > 0)
{
foreach (var item in queryParams)
{
request.AddQueryParameter(item.Key, item.Value);
}
}
if (param != null)
{
request.AddJsonBody(param);
}
if (headers != null)
{
defaultHeader = headers;
}
try
{
request.AddHeaders(defaultHeader);
var restResponse = await restClient.ExecutePostAsync(request);
return HandleResponse(restResponse, resource, param);
}
catch (Exception ex)
{
return "";
}
}
public async Task<string> PostFormDataAsync(string host, string resource, Dictionary<string, object> param)
{
var options = new RestClientOptions(host)
{
ThrowOnAnyError = true
};
var restClient = new RestClient(options);
var request = new RestRequest(resource);
if (param != null && param.Count > 0)
{
foreach (var item in param)
{
request.AddParameter(item.Key, item.Value.ToJson(), ParameterType.RequestBody);
}
}
try
{
request.AddHeaders(defaultHeader);
var restResponse = await restClient.ExecutePostAsync(request);
return HandleResponse(restResponse, resource, param);
}
catch (Exception ex)
{
return "";
}
}
private string HandleResponse(RestResponse restResponse, string resource, object param)
{
if (!restResponse.IsSuccessful)
{
return JsonConvert.SerializeObject(new {info = restResponse.ErrorMessage, code = -1});
}
try
{
JObject jt = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(restResponse.Content);
int code = jt["code"].ObjToInt();
if (code != 0 && code != 401)
{
}
}
catch (Exception ex)
{
}
return restResponse.Content;
}
public async Task<bool> DownloadFile(string fileName, string host, string resource,
Dictionary<string, object> param = null, Dictionary<string, string> headers = null)
{
var options = new RestClientOptions(host)
{
ThrowOnAnyError = true,
};
var restClient = new RestClient(options);
var request = new RestRequest(resource);
if (param != null && param.Count > 0)
{
foreach (var item in param.Where(e => e.Value != null))
{
request.AddQueryParameter(item.Key, item.Value.ToString());
}
}
if (headers != null)
{
defaultHeader = headers;
}
request.AddHeaders(defaultHeader);
var restResponse = await restClient.DownloadDataAsync(request);
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
using (FileStream pFileStream = new FileStream(fileName, FileMode.OpenOrCreate))
{
pFileStream.Write(restResponse, 0, restResponse.Length);
}
return System.IO.File.Exists(fileName);
}
}
}