173 lines
5.9 KiB
C#
173 lines
5.9 KiB
C#
using LMS.Tools.FileTool;
|
||
using Microsoft.Extensions.Logging;
|
||
using System.Text;
|
||
|
||
namespace LMS.Tools.HttpTool
|
||
{
|
||
/// <summary>
|
||
/// HTTP网络请求服务
|
||
/// </summary>
|
||
public class HttpService : IHttpService
|
||
{
|
||
private readonly IHttpClientFactory _httpClientFactory;
|
||
private readonly ILogger<HttpService> _logger;
|
||
|
||
public HttpService(
|
||
IHttpClientFactory httpClientFactory,
|
||
ILogger<HttpService> logger)
|
||
{
|
||
_httpClientFactory = httpClientFactory;
|
||
_logger = logger;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 下载文件并返回字节数组
|
||
/// </summary>
|
||
/// <param name="url">文件URL</param>
|
||
/// <returns>文件字节数组</returns>
|
||
public async Task<byte[]?> DownloadFileAsync(string url, double maxFileSize)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(url))
|
||
throw new ArgumentException("URL不能为空", nameof(url));
|
||
|
||
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
|
||
throw new ArgumentException("无效的URL格式", nameof(url));
|
||
|
||
using var httpClient = _httpClientFactory.CreateClient("HttpService");
|
||
using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
|
||
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
throw new HttpRequestException($"HTTP请求失败,状态码: {response.StatusCode}");
|
||
}
|
||
|
||
// 检查文件大小
|
||
if (response.Content.Headers.ContentLength.HasValue)
|
||
{
|
||
if (response.Content.Headers.ContentLength.Value > maxFileSize * 1024 * 1024)
|
||
{
|
||
throw new InvalidOperationException($"文件大小({response.Content.Headers.ContentLength.Value} bytes)超过限制({maxFileSize * 1024 * 1024} bytes)");
|
||
}
|
||
}
|
||
|
||
var fileBytes = await response.Content.ReadAsByteArrayAsync();
|
||
|
||
if (fileBytes.Length > maxFileSize * 1024 * 1024)
|
||
{
|
||
throw new InvalidOperationException($"下载的文件大小({fileBytes.Length} bytes)超过限制({maxFileSize * 1024 * 1024} bytes)");
|
||
}
|
||
|
||
return fileBytes;
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
_logger.LogError(ex, "HTTP请求异常: {Url}", url);
|
||
throw;
|
||
}
|
||
catch (TaskCanceledException ex)
|
||
{
|
||
_logger.LogError(ex, "请求超时: {Url}", url);
|
||
throw new TimeoutException("请求超时", ex);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "下载文件失败: {Url}", url);
|
||
throw;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送GET请求
|
||
/// </summary>
|
||
/// <param name="url">请求URL</param>
|
||
/// <returns>响应内容</returns>
|
||
public async Task<string> GetAsync(string url)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(url))
|
||
throw new ArgumentException("URL不能为空", nameof(url));
|
||
|
||
using var httpClient = _httpClientFactory.CreateClient("HttpService");
|
||
var response = await httpClient.GetStringAsync(url);
|
||
return response;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "GET请求失败: {Url}", url);
|
||
throw;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送POST请求
|
||
/// </summary>
|
||
/// <param name="url">请求URL</param>
|
||
/// <param name="content">请求内容</param>
|
||
/// <returns>响应内容</returns>
|
||
public async Task<string> PostAsync(string url, string content)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(url))
|
||
throw new ArgumentException("URL不能为空", nameof(url));
|
||
|
||
using var httpClient = _httpClientFactory.CreateClient("HttpService");
|
||
var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
|
||
var response = await httpClient.PostAsync(url, httpContent);
|
||
|
||
response.EnsureSuccessStatusCode();
|
||
return await response.Content.ReadAsStringAsync();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "POST请求失败: {Url}", url);
|
||
throw;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查URL是否可访问
|
||
/// </summary>
|
||
/// <param name="url">要检查的URL</param>
|
||
/// <returns>是否可访问</returns>
|
||
public async Task<bool> IsUrlAccessibleAsync(string url)
|
||
{
|
||
try
|
||
{
|
||
using var httpClient = _httpClientFactory.CreateClient("HttpService");
|
||
using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
|
||
return response.IsSuccessStatusCode;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取URL的Content-Type
|
||
/// </summary>
|
||
/// <param name="url">要检查的URL</param>
|
||
/// <returns>Content-Type</returns>
|
||
public async Task<string?> GetContentTypeAsync(string url)
|
||
{
|
||
try
|
||
{
|
||
using var httpClient = _httpClientFactory.CreateClient("HttpService");
|
||
using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
return response.Content.Headers.ContentType?.MediaType;
|
||
}
|
||
return null;
|
||
}
|
||
catch
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
}
|
||
} |