C# 如何进行HTTP POST请求 - 使用HttpClient发送JSON数据

来源:这里教程网 时间:2026-02-21 17:32:48 作者:

在C#中使用 HttpClient 发送 HTTP POST 请求并提交 JSON 数据,是现代 .NET 开发中的常见需求。以下是一个简洁、实用的实现方式,适用于 .NET 6 及以上版本。

创建 HttpClient 并发送 JSON 数据

你需要将数据序列化为 JSON,设置正确的请求头(Content-Type: application/json),然后通过 POST 发送到目标 API。

使用 System.Text.Json 序列化对象为 JSON 字符串 StringContent 包装内容,并指定编码和媒体类型 调用 PostAsync 方法发送请求

示例代码:

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);

注意事项与最佳实践

重用 HttpClient 实例:避免频繁创建 HttpClient,应全局或单例使用,防止套接字耗尽 处理异常:始终用 try-catch 捕获 HttpRequestException 设置超时:可通过 HttpClient.Timeout 属性控制请求最长等待时间 添加请求头:如需认证,可在发送前添加 headers,例如:
client.DefaultRequestHeaders.Add("Authorization", "Bearer xxx")

基本上就这些。只要掌握序列化、StringContent 和 PostAsync 的配合,就能轻松完成 JSON 提交。

相关推荐