HttpClient CS2046
时间: 2023-12-19 18:30:22 浏览: 100
HttpClient是.NET Framework 4.5中引入的一个类,用于发送HTTP请求并接收HTTP响应。它提供了一种简单的方法来与Web API进行通信。以下是一个使用HttpClient发送POST请求的示例:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpClientExample
{
class Program
{
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
var postData = "{\"name\":\"John Doe\",\"age\":30}";
var httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync("http://example.com/api/users", httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
```
此示例使用HttpClient发送一个POST请求,将JSON数据发送到Web API的“/api/users”端点。在发送请求时,我们将JSON数据作为字符串传递给StringContent构造函数,并将Content-Type标头设置为“application/json”。在接收到响应后,我们使用ReadAsStringAsync方法将响应内容作为字符串读取,并将其打印到控制台上。
阅读全文
相关推荐

















