using System.IO; using System.Net; using System.Net.Http; using System.Text; namespace Ramitta.lib { public static class HttpHelper { // 异步发送HTTP GET请求 public static async Task SendHttpGetAsync(string url, int timeout = 10000) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeout; using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { return await reader.ReadToEndAsync(); } } catch (Exception ex) { throw new Exception($"GET请求失败: {ex.Message}"); } } public static async Task SendHttpPostAsync(string url, string jsonData, int timeout = 10000, bool bypassProxy = true) { try { var handler = new HttpClientHandler(); if (bypassProxy) { // 方法1:不使用代理 handler.UseProxy = false; handler.Proxy = null; // 方法2:指定某些地址不代理 // handler.Proxy = new WebProxy(); // handler.UseProxy = true; // handler.PreAuthenticate = true; } else { // 使用系统代理 handler.UseProxy = true; handler.Proxy = WebRequest.GetSystemWebProxy(); } // 可选:禁用自动重定向 handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { client.Timeout = TimeSpan.FromMilliseconds(timeout); var content = new StringContent(jsonData, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); // 确保成功状态 if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); throw new Exception($"HTTP错误 {(int)response.StatusCode} ({response.StatusCode}): {errorContent}"); } return await response.Content.ReadAsStringAsync(); } } catch (HttpRequestException ex) { throw new Exception("HTTP请求失败: " + ex.Message); } catch (TaskCanceledException ex) { throw new Exception("请求超时: " + ex.Message); } catch (Exception ex) { throw new Exception("POST请求失败: " + ex.Message); } } } }