using System.Net.Http; using System.Text; using Newtonsoft.Json; public class HttpHelper { private static readonly HttpClient _httpClient = new HttpClient(); // POST请求(提交JSON数据) public static async Task<TResponse> PostAsync<TRequest, TResponse>(string url, TRequest data) { try { string json = JsonConvert.SerializeObject(data); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await _httpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); string responseJson = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TResponse>(responseJson); } catch (HttpRequestException ex) { Console.WriteLine($"HTTP请求错误: {ex.Message}"); return default; } catch (Exception ex) { Console.WriteLine($"POST请求失败: {ex.Message}"); return default; } } // 调用示例 public static async Task TestPost() { var user = new { Name = "张三", Age = 25 }; var result = await PostAsync<object, string>("https://httpbin.org/post", user); Console.WriteLine("POST响应结果: " + result); } }