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

public static async Task 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数据的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1442693.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 19:18:01
下一篇 2025年12月17日 19:18:11

相关推荐

发表回复

登录后才能评论
关注微信