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 RequestAsync(string address, Dictionary 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 RequestStringAsync(string address, Dictionary 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 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); } } } }