HttpRequestHelper
using System; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; // 需要安装 Newtonsoft.Json NuGet 包 public class HttpRequestHelper { private readonly HttpClient _httpClient; private readonly string _baseUrl; public HttpRequestHelper(string baseUrl) { _httpClient = new HttpClient(); _baseUrl = baseUrl; } public async Task<T> GetAsync<T>(string endpoint) { try { var url = $"{_baseUrl}{endpoint}"; var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(content); } catch (HttpRequestException ex) { Console.WriteLine($"Request error: {ex.Message}"); throw; } } public async Task<T> PostAsync<T, TRequestBody>(string endpoint, TRequestBody body) { try { var url = $"{_baseUrl}{endpoint}"; var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(responseContent); } catch (HttpRequestException ex) { Console.WriteLine($"Request error: {ex.Message}"); throw; } } }
以下是如何使用 HttpRequestHelper
类来发送 GET 和 POST 请求的示例:
using System; using System.Threading.Tasks; public class Example { public static async Task Main(string[] args) { var helper = new HttpRequestHelper("https://api.example.com"); // 发送 GET 请求 var getResponse = await helper.GetAsync<GetResponse>("endpoint/get"); Console.WriteLine($"GET response: {JsonConvert.SerializeObject(getResponse, Formatting.Indented)}"); // 发送 POST 请求 var postRequestBody = new PostRequestBody { Property1 = "Value1", Property2 = 123 }; var postResponse = await helper.PostAsync<PostResponse, PostRequestBody>("endpoint/post", postRequestBody); Console.WriteLine($"POST response: {JsonConvert.SerializeObject(postResponse, Formatting.Indented)}"); } public class GetResponse { // 根据你的 API 响应定义属性 public string Property1 { get; set; } public int Property2 { get; set; } } public class PostRequestBody { // 根据你的 API 请求体定义属性 public string Property1 { get; set; } public int Property2 { get; set; } } public class PostResponse { // 根据你的 API 响应定义属性 public string Message { get; set; } public bool Success { get; set; } } }
注意事项
- 错误处理:示例中的错误处理相对简单,仅输出错误信息并抛出异常。在实际应用中,你可能需要更复杂的错误处理逻辑。
- 依赖项:示例使用了
Newtonsoft.Json
库来序列化和反序列化 JSON。你需要通过 NuGet 包管理器安装Newtonsoft.Json
。 - HttpClient 生命周期:
HttpClient
是一个资源密集型对象,建议重用HttpClient
实例而不是每次请求都创建一个新的实例。