当前位置: 代码网 > it编程>编程语言>Asp.net > C#使用HttpClient发起HTTP请求的完整指南

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

2025年11月06日 Asp.net 我要评论
1、简述在现代应用中,调用 restful api 已成为日常开发中不可或缺的一部分。无论你在开发桌面程序、web 服务还是后台任务,httpclient 都是 .net 提供的官方网络请求利器。本文

1、简述

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

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

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
反序列化 jsonjsonserializer.deserialize<t>()

7、结语

通过本文你学到了:

  • 如何在 c# 中使用 httpclient 发起各种 http 请求;
  • 如何发送 json、处理响应与异常;
  • 如何在实际项目中使用 httpclientfactory 优化性能。

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

以上就是c#使用httpclient发起http请求的完整指南的详细内容,更多关于c# httpclient发起http请求的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com