From 8d8a887c42f0d41a41eaa17c323d8db7a48a0230 Mon Sep 17 00:00:00 2001 From: 2dust <31833384+2dust@users.noreply.github.com> Date: Thu, 6 Mar 2025 10:47:57 +0800 Subject: [PATCH] Update HttpClientHelper.cs AI-optimized code --- v2rayN/ServiceLib/Common/HttpClientHelper.cs | 23 ++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/v2rayN/ServiceLib/Common/HttpClientHelper.cs b/v2rayN/ServiceLib/Common/HttpClientHelper.cs index d2d4924f..f532062e 100644 --- a/v2rayN/ServiceLib/Common/HttpClientHelper.cs +++ b/v2rayN/ServiceLib/Common/HttpClientHelper.cs @@ -18,12 +18,17 @@ namespace ServiceLib.Common public static HttpClientHelper Instance => _instance.Value; private readonly HttpClient httpClient; - private HttpClientHelper(HttpClient httpClient) => this.httpClient = httpClient; + private HttpClientHelper(HttpClient httpClient) + { + this.httpClient = httpClient; + } public async Task TryGetAsync(string url) { if (url.IsNullOrEmpty()) + { return null; + } try { @@ -39,14 +44,18 @@ namespace ServiceLib.Common public async Task GetAsync(string url) { if (url.IsNullOrEmpty()) + { return null; + } return await httpClient.GetStringAsync(url); } public async Task GetAsync(HttpClient client, string url, CancellationToken token = default) { if (url.IsNullOrEmpty()) + { return null; + } return await client.GetStringAsync(url, token); } @@ -55,13 +64,13 @@ namespace ServiceLib.Common var jsonContent = JsonUtils.Serialize(headers); var content = new StringContent(jsonContent, Encoding.UTF8, MediaTypeNames.Application.Json); - var result = await httpClient.PutAsync(url, content); + await httpClient.PutAsync(url, content); } public async Task PatchAsync(string url, Dictionary headers) { var myContent = JsonUtils.Serialize(headers); - var buffer = System.Text.Encoding.UTF8.GetBytes(myContent); + var buffer = Encoding.UTF8.GetBytes(myContent); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); @@ -78,12 +87,16 @@ namespace ServiceLib.Common ArgumentNullException.ThrowIfNull(url); ArgumentNullException.ThrowIfNull(fileName); if (File.Exists(fileName)) + { File.Delete(fileName); + } using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); if (!response.IsSuccessStatusCode) + { throw new Exception(response.StatusCode.ToString()); + } var total = response.Content.Headers.ContentLength ?? -1L; var canReportProgress = total != -1 && progress != null; @@ -102,7 +115,9 @@ namespace ServiceLib.Common totalRead += read; if (read == 0) + { break; + } await file.WriteAsync(buffer.AsMemory(0, read), token); if (canReportProgress) @@ -173,7 +188,7 @@ namespace ServiceLib.Common totalRead += read; - var ts = (DateTime.Now - totalDatetime); + var ts = DateTime.Now - totalDatetime; if (progress != null && ts.Seconds > totalSecond) { totalSecond = ts.Seconds;