在C#开发中,向服务器接口发送POST请求是非常常见的操作,比如提交表单、调用Web API、上传数据等。过去常用WebClient或HttpWebRequest,现在更推荐用HttpClient,它语法简单且支持异步。下面从最基础的用法讲起,帮你掌握C#发送POST请求的完整流程。

一、使用HttpClient发送JSON格式POST请求
这是目前最主流的方式。我们需要把数据序列化成JSON字符串,放进请求体里,同时设置Content-Type为application/json。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建HttpClient实例,实际项目中建议用单例或依赖注入
using HttpClient client = new HttpClient();
// 要发送的数据,这里用匿名对象演示
var data = new
{
username = "test",
password = "123456"
};
// 序列化为JSON字符串(需引用System.Text.Json)
string json = System.Text.Json.JsonSerializer.Serialize(data);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送POST请求
HttpResponseMessage response = await client.PostAsync("https://ipipp.com/api/login", content);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取返回内容
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("服务器返回:" + result);
}
}
二、发送表单格式POST请求
有些老接口要求使用表单形式(application/x-www-form-urlencoded)提交数据,可以用FormUrlEncodedContent来处理。
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using HttpClient client = new HttpClient();
// 表单键值对
var values = new Dictionary<string, string>
{
{ "name", "张三" },
{ "age", "20" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://ipipp.com/api/user", content);
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
三、常见注意事项
- HttpClient不要每次请求都new,否则高并发下会耗尽端口,应使用静态实例或AddHttpClient。
- 异步方法记得加await,否则可能拿不到完整响应。
- 如果接口需要鉴权,可在请求头里加Authorization,例如client.DefaultRequestHeaders.Add("Authorization", "Bearer token")。
- 本地调试可用127.0.0.1或192.168.0.1地址,不受外网限制。
四、小结
用C#发送POST请求核心就是准备好HttpClient、构造正确的内容类型和请求体,然后调用PostAsync。掌握上面两种代码写法,基本能应付大部分后端接口对接场景。遇到复杂需求时,再结合具体API文档调整参数即可。
C#POST请求HttpClient修改时间:2026-07-30 13:00:27