How do you send a POST request in C#?
In C#, you can send a POST request using the HttpClient class. Here is an example code:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
// 设置请求的地址
string url = "http://example.com/api/post";
// 构造请求参数
var postData = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2" }
};
// 创建HttpContent对象并转换为字节数组
HttpContent content = new FormUrlEncodedContent(postData);
// 发送POST请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("请求失败,状态码:" + response.StatusCode);
}
}
}
}
This example demonstrates using the HttpClient class to send a POST request and encoding the request parameters in form format. The response content can be read using the response.Content.ReadAsStringAsync() method.
Please note that the PostAsync method in this example is an asynchronous method that can be awaited using the await keyword for completion.