Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# httpclient

作者:呐爱淡了   发布日期:2025-10-13   浏览:48

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

class Program
{
    static async Task Main(string[] args)
    {
        // 创建一个 HttpClient 实例
        using (HttpClient client = new HttpClient())
        {
            try
            {
                // 发送 GET 请求并获取响应
                HttpResponseMessage response = await client.GetAsync("https://api.github.com");

                // 确保请求成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();

                // 输出响应内容
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                // 捕获并处理请求异常
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }
    }
}

解释说明

  1. 创建 HttpClient 实例:

    • 使用 HttpClient 类来发送 HTTP 请求和接收响应。HttpClient 是线程安全的,建议在整个应用程序生命周期内重用同一个实例。
  2. 发送 GET 请求:

    • 使用 GetAsync 方法发送 GET 请求到指定的 URL(本例中为 GitHub API 的根 URL)。
  3. 确保请求成功:

    • EnsureSuccessStatusCode 方法会抛出异常,如果响应状态码不在 200-299 范围内。
  4. 读取响应内容:

    • 使用 ReadAsStringAsync 方法将响应内容读取为字符串。
  5. 异常处理:

    • 使用 try-catch 块捕获并处理可能的 HttpRequestException 异常。
  6. 输出响应内容:

    • 将响应内容打印到控制台。

如果你需要更多关于 HttpClient 的详细信息或有其他问题,请告诉我!

上一篇:c# dictionary

下一篇:c# ??

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站