在 C# 中,可以使用 HttpClient 类来打开网页并获取网页接口。以下是一个示例:

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://example.com/api");

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

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

                // 处理响应内容
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException ex)
            {
                // 处理异常
                Console.WriteLine($"请求发生异常: {ex.Message}");
            }
        }
    }
}

在上面的示例中,我们使用 HttpClient 类的 GetAsync 方法来发送 GET 请求,并使用 ReadAsStringAsync 方法来读取响应内容。通过 EnsureSuccessStatusCode 方法,我们可以确保请求成功

C# 如何打开网页获取网页接口

原文地址: http://www.cveoy.top/t/topic/ii3g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录