admin 发表于 2024-5-19 17:28:28

C#取网页内容

在C#中,你可以使用HttpClient类来发送HTTP请求并获取网页内容。以下是一个简单的示例代码,展示了如何使用HttpClient获取指定网页的内容:

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

class Program
{
    static async Task Main(string[] args)
    {
      using (HttpClient client = new HttpClient())
      {
            // 设置目标网页URL
            string url = "http://example.com";

            try
            {
                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);

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

                // 读取响应内容作为字符串
                string content = await response.Content.ReadAsStringAsync();

                // 输出网页内容
                Console.WriteLine(content);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
      }
    }
}

确保你的项目中引用了System.Net.Http命名空间。这段代码使用了async和await关键字来处理异步操作。HttpClient的GetAsync方法用于发送HTTP GET请求,EnsureSuccessStatusCode方法用于确保响应状态码表示成功,ReadAsStringAsync方法用于读取响应内容为字符串。如果在获取网页内容过程中发生异常,将捕获异常并输出错误信息。

页: [1]
查看完整版本: C#取网页内容