C#:HttpClient 发起 HTTP 请求的技术指南

admin
1
2025-12-29

🌐 1、简述

在现代应用中,调用 RESTful API 已成为日常开发中不可或缺的一部分。无论你在开发桌面程序、Web 服务还是后台任务,HttpClient 都是 .NET 提供的官方网络请求利器。

本文将带你深入了解 HttpClient 的使用方式,并通过多个实践样例帮助你快速掌握它。

image-utok.png


2、HttpClient 是什么?

HttpClient 是 .NET 中用于发送 HTTP 请求和接收响应的核心类,属于命名空间:

using System.Net.Http;

它支持:

✅ GET / POST / PUT / DELETE 等 HTTP 方法

✅ 异步请求(基于 async/await)

✅ 自定义请求头与内容类型

✅ 连接复用与超时控制

✅ JSON 数据序列化与反序列化

创建 HttpClient 实例

最基础的创建方式如下:

var client = new HttpClient();

但是要注意:

⚠️ 不要在每次请求时 new HttpClient()!
因为它会导致连接未及时释放,引起端口耗尽问题。

正确的做法是:

🔥 在应用生命周期内 重用 HttpClient 实例

🔥 或使用 HttpClientFactory(在 ASP.NET Core 中推荐)。


3、实践样例

下面我们从最常见的 GET 与 POST 请求 开始。

🟢 示例 1:GET 请求

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();

        var url = "https://api.github.com/repos/dotnet/runtime";
        // 设置 User-Agent,否则 GitHub API 会拒绝访问
        client.DefaultRequestHeaders.Add("User-Agent", "CSharpHttpClientDemo");

        var response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode(); // 确保状态码 200-299

        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine("返回内容:");
        Console.WriteLine(content);
    }
}

✅ 输出为 JSON 格式的仓库信息。

🟠 示例 2:POST 请求(发送 JSON 数据)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();

        var url = "https://httpbin.org/post";
        var data = new { Name = "Alice", Age = 25 };
        var json = JsonSerializer.Serialize(data);

        var content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);

        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine("响应内容:");
        Console.WriteLine(result);
    }
}

📝 该示例演示了如何:

🔥 将 C# 对象序列化为 JSON;

🔥 使用 StringContent 设置请求体;

🔥 指定 Content-Typeapplication/json


4、其他常用操作

1️⃣ 设置请求头

client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here");
client.DefaultRequestHeaders.Add("Accept", "application/json");

2️⃣ PUT / DELETE 请求

// PUT 请求
var putContent = new StringContent("{\"name\":\"Bob\"}", Encoding.UTF8, "application/json");
var putResponse = await client.PutAsync("https://httpbin.org/put", putContent);

// DELETE 请求
var deleteResponse = await client.DeleteAsync("https://httpbin.org/delete");

3️⃣ 超时与异常处理

client.Timeout = TimeSpan.FromSeconds(10);

try
{
    var response = await client.GetAsync("https://slowwly.robertomurray.co.uk/delay/5000/url/http://example.com");
    Console.WriteLine(await response.Content.ReadAsStringAsync());
}
catch (TaskCanceledException)
{
    Console.WriteLine("请求超时!");
}

4️⃣ 反序列化 JSON 响应

using System.Text.Json;

var jsonStr = await response.Content.ReadAsStringAsync();
var repoInfo = JsonSerializer.Deserialize<Repo>(jsonStr);

Console.WriteLine($"项目名称:{repoInfo.name}");
Console.WriteLine($"Star 数:{repoInfo.stargazers_count}");

class Repo
{
    public string name { get; set; }
    public int stargazers_count { get; set; }
}

5、天气查询程序 🌤️

这是一个实际的 API 调用案例,使用 Open-Meteo API 查询天气:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();

        string url = "https://api.open-meteo.com/v1/forecast?latitude=35&longitude=139&current_weather=true";
        var response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync();
        var weather = JsonSerializer.Deserialize<WeatherResponse>(json);

        Console.WriteLine($"当前温度:{weather.current_weather.temperature} °C");
        Console.WriteLine($"风速:{weather.current_weather.windspeed} km/h");
    }
}

class WeatherResponse
{
    public CurrentWeather current_weather { get; set; }
}

class CurrentWeather
{
    public double temperature { get; set; }
    public double windspeed { get; set; }
}

运行结果示例:

当前温度:21.3 °C
风速:5.2 km/h

6、HttpClientFactory(进阶用法)

在 ASP.NET Core 中,推荐使用 IHttpClientFactory 管理 HttpClient 实例:

// Startup.cs
services.AddHttpClient("GitHub", client =>
{
    client.BaseAddress = new Uri("https://api.github.com/");
    client.DefaultRequestHeaders.Add("User-Agent", "MyApp");
});

使用时:

public class GitHubService
{
    private readonly HttpClient _client;

    public GitHubService(IHttpClientFactory factory)
    {
        _client = factory.CreateClient("GitHub");
    }

    public async Task<string> GetRepoAsync(string name)
    {
        var response = await _client.GetAsync($"repos/{name}");
        return await response.Content.ReadAsStringAsync();
    }
}

✅ 优点:

🔥 自动管理连接生命周期;

🔥 支持命名客户端;

🔥 避免 Socket 耗尽;

🔥 更易于测试与扩展。

功能 方法
GET 请求 GetAsync()
POST 请求 PostAsync()
PUT 请求 PutAsync()
DELETE 请求 DeleteAsync()
添加头部 DefaultRequestHeaders.Add()
设置超时 client.Timeout
反序列化 JSON JsonSerializer.Deserialize<T>()

7、结语 💡

通过本文你学到了:

🔥 如何在 C# 中使用 HttpClient 发起各种 HTTP 请求;

🔥 如何发送 JSON、处理响应与异常;

🔥 如何在实际项目中使用 HttpClientFactory 优化性能。

建议:在生产环境中,始终重用 HttpClient 或使用 IHttpClientFactory,并注意请求超时与重试机制。

动物装饰