添加项目文件。

This commit is contained in:
2025-02-25 22:28:49 +08:00
parent 07e26cc93e
commit 1a7bdb585a
32 changed files with 1601 additions and 0 deletions

106
Utils.cs Normal file
View File

@@ -0,0 +1,106 @@
using System.Net;
namespace MegghysAPI
{
public static class Utils
{
public static readonly HttpClient _client = new(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.All,
})
{
//Timeout = new TimeSpan(0, 0, 15),
};
public static HttpResponseMessage Request(string address) => RequestAsync(address).Result;
public static async Task<HttpResponseMessage?> RequestAsync(string address, Dictionary<string, string> header = null)
{
try
{
var uri = new Uri(address);
var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (header?.Count > 0)
{
foreach (var h in header)
{
request.Headers.TryAddWithoutValidation(h.Key, h.Value);
}
}
return await _client.SendAsync(request);
}
catch (Exception ex)
{
Logs.Error((ex.InnerException ?? ex).Message);
return null;
}
}
public static async Task<string?> RequestStringAsync(string address, Dictionary<string, string> header = null)
{
try
{
var uri = new Uri(address);
if (uri.Host.EndsWith("bilibili.com"))
{
header ??= [];
header.TryAdd("Referer", "https://" + uri.Host);
}
var result = await RequestAsync(address, header);
var content = await result?.Content.ReadAsStringAsync();
if (result?.IsSuccessStatusCode != true)
{
Logs.Warn($"请求失败: {address} {result?.StatusCode}: {content[..100]}");
}
return content;
}
catch (Exception ex)
{
Logs.Error(ex);
return null;
}
}
public static string RequestString(string address, Dictionary<string, string> header = null) => RequestStringAsync(address, header).Result;
public static async Task<(HttpStatusCode code, byte[] data)> DownloadBytesAsync(string uri)
{
try
{
return (HttpStatusCode.OK, await _client.GetByteArrayAsync(uri));
}
catch (HttpRequestException ex)
{
return (ex.StatusCode ?? HttpStatusCode.BadRequest, null);
}
catch (Exception ex)
{
Logs.Error(ex); // 返回false下载失败
return (HttpStatusCode.BadRequest, null);
}
}
public static async Task<(HttpStatusCode code, string path)> DownloadFileAsync(string url, string path = null, bool resume = true)
{
path ??= Datas.TempFilePath;
var dire = Path.GetDirectoryName(path);
if (!Directory.Exists(dire))
Directory.CreateDirectory(dire);
try
{
var result = await DownloadBytesAsync(url);
if (result.code == HttpStatusCode.OK)
{
await File.WriteAllBytesAsync(path, result.data);
return (HttpStatusCode.OK, path);
}
else
return (result.code, null);
}
catch (HttpRequestException webex)
{
return (webex.StatusCode ?? HttpStatusCode.BadRequest, null);
}
catch (Exception ex)
{
Logs.Error(ex); // 返回false下载失败
return (HttpStatusCode.BadRequest, null);
}
}
}
}