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

在C#中使用HttpClient发送JSON POST请求需序列化对象为JSON、用StringContent包装并设置application/json类型,再调用PostAsync;应重用HttpClient实例、捕获HttpRequestException、设置超时及必要请求头。

c# 如何进行http post请求 - 使用httpclient发送json数据

在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 请求。

Getsound Getsound

基于当前天气条件生成个性化音景音乐

Getsound 212 查看详情 Getsound
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 提交。

以上就是C# 如何进行HTTP POST请求 - 使用HttpClient发送JSON数据的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。