C#:
发出 HTTP 请求
How to:(如何做:)
C#里发HTTP请求简单直接。先看看HttpClient的用法:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}运行后输出(假设响应是JSON):
{"name": "Example", "value": "123"}Deep Dive(深入了解)
在.NET框架出现之前,发起HTTP请求可能涉及更底层的操作,例如直接使用sockets。HttpClient是.NET 4.5中引入的,提供了一组易于使用的方法来发送HTTP请求。
除了HttpClient,还有别的选择,如WebRequest,以及第三方库,如RestSharp。但HttpClient是现代、异步编程的首选。
HttpClient用起来方便,但需要注意资源管理。一般推荐作为单例使用,不要为每个请求创建新实例。
See Also(另请参阅)
- HttpClient Class - 官方文档,详细介绍
HttpClient的使用。 - Implementing HTTP call retries with exponential backoff with Polly - 如何使用Polly实现 HTTP 调用重试与退避策略。