在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 Task<string> PostAsJsonAsync(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 提交。
以上就是C# 如何进行HTTP POST请求 - 使用HttpClient发送JSON数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号