C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# HttpClient发起HTTP请求

C#使用HttpClient发起HTTP请求的完整指南

作者:拾荒的小海螺

本文介绍了在.NET中使用HttpClient进行RESTful API调用的方法,HttpClient是.NET中处理HTTP请求的核心类,支持多种HTTP方法、异步请求和JSON序列化,文章强调要重用HttpClient实例以避免端口耗尽问题,需要的朋友可以参考下

1、简述

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

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

2、HttpClient 是什么?

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

using System.Net.Http;

它支持:

创建 HttpClient 实例

最基础的创建方式如下:

var client = new HttpClient();

但是要注意:

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

正确的做法是:

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);
    }
}

该示例演示了如何:

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();
    }
}

优点:

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

7、结语

通过本文你学到了:

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

以上就是C#使用HttpClient发起HTTP请求的完整指南的详细内容,更多关于C# HttpClient发起HTTP请求的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文