using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
// 设置请求的URL
string url = "https://example.com/api/data";
// 创建要发送的JSON数据
var content = new StringContent(
"{\"name\":\"John\", \"age\":30}",
Encoding.UTF8,
"application/json"
);
try
{
// 发送POST请求并获取响应
HttpResponseMessage response = await client.PostAsync(url, content);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"请求错误: {e.Message}");
}
}
}
}
HttpClient 是一个可重用的对象,建议在应用程序的生命周期内只创建一次。application/json)。这个示例展示了如何使用C#中的HttpClient类发送POST请求并处理响应。
上一篇:c# 单例
下一篇:c#switch
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站