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