1 public class HttpHelper 2 { 3 /// <summary> 4 /// Get the content of a file from the specified URL. 5 /// </summary> 6 /// <param name="url">The URL to request.</param> 7 /// <param name="method">The HTTP request method.</param> 8 /// <param name="postData">The data for POST requests (optional).</param> 9 /// <returns>The content of the file.</returns> 10 public static async Task<string> GetFileContent(string url, HttpMethod method, string postData = null) 11 { 12 using (HttpClient client = new HttpClient()) 13 { 14 HttpRequestMessage request = new HttpRequestMessage(method, url); 15 if (method == HttpMethod.Post && !string.IsNullOrEmpty(postData)) 16 { 17 request.Content = new StringContent(postData); 18 } 19 20 HttpResponseMessage response = await client.SendAsync(request); 21 if (response.IsSuccessStatusCode) 22 { 23 return await response.Content.ReadAsStringAsync(); 24 } 25 else 26 { 27 Console.WriteLine($"Request failed: {response.StatusCode}"); 28 return null; 29 } 30 } 31 } 32 33 /// <summary> 34 /// Make an HTTP request. 35 /// </summary> 36 /// <param name="baseUrl">The target URL.</param> 37 /// <param name="method">The request method.</param> 38 /// <param name="requestBody">The request body parameters.</param> 39 /// <returns></returns> 40 public static string HttpRequest(string baseUrl, Method method, RestRequest requestBody) 41 { 42 try 43 { 44 var client = new RestClient(baseUrl); 45 46 requestBody.Method = method; 47 var response = client.Execute(requestBody); 48 if (response.StatusCode == HttpStatusCode.OK) 49 { 50 return response.Content; 51 } 52 53 throw new Exception("HTTP request result error: " + response.ErrorMessage); 54 } 55 catch (Exception ex) 56 { 57 throw new Exception("HTTP request failed: " + ex.Message); 58 } 59 } 60 }
请注意,当 response.StatusCode 状态不是ok时,我会抛出异常。如果不符合业务,请自行修改。
源码地址:https://github.com/yycb1994/DotNet.Working.Notes/tree/main/Working.Notes/Working.Tools
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)