c#怎么发送post http请求 携带json参数
时间: 2023-10-12 15:05:56 浏览: 74
在 C# 中发送 POST 请求并携带 JSON 参数可以使用 `HttpClient` 类。下面是一个示例代码:
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static async Task Main(string[] args)
{
var url = "https://example.com/api";
var json = "{\"name\":\"John\", \"age\":30}";
using var httpClient = new HttpClient();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
```
在上面的代码中,我们首先指定了要请求的 URL 地址和要发送的 JSON 数据。然后,我们创建了一个 `HttpClient` 实例,并使用 `StringContent` 类将 JSON 数据转换为 HTTP 内容。最后,我们使用 `PostAsync` 方法发送 POST 请求,并从响应中读取内容。注意,在 `using` 代码块中使用 HttpClient 和 StringContent 可以确保它们在使用完毕后被正确地释放。