

新闻资讯
技术学院在C#中使用HttpClient发送JSON POST请求需序列化对象为JSON、用StringContent包装并设置application/json类型,再调用PostAsync;应重用HttpClient实例、捕获HttpRequestException、设置超时及必要请求头。
在C#中使用 HttpClient 发送 HTTP POST 请求并提交 JSON 数据,是现代 .NET 开发中的常见需求。以下是一个简洁、实用的实现方式,适用于 .NET 6 及以上版本。
你需要将数据序列化为 JSON,设置正确的请求头(Content-Type: application/json),然后通过 POST 发送到目标 API。
示例代码:
using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; public class Program { private static readonly HttpClient client = new HttpClient(); public static async Task Main() { var userData = new { Name = "张三", Age = 30 }; var json = JsonSerializer.Serialize(userData); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync("https://httpbin.org/post", content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"请求出错: {e.Message}"); } } }
为了提高代码可维护性,可以封装成泛型方法,支持任意对象发送 JSON POST 请求。
public static async TaskPostAsJsonAsync(string url, object data) { var json = JsonSerializer.Serialize(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); }
调用方式:
var result = await PostAsJsonAsync("https://api.example.com/user", new { Name = "李四", Email = "lisi@example.com" });
Console.WriteLine(result);
client.DefaultRequestHeaders.Add("Authorization", "Bearer xxx")
基本上就这些。只要掌握序列化、StringContent 和 PostAsync 的配合,就能轻松完成 JSON 提交。