C#获取HTML内容
在C#中,你可以使用HttpClient类来发送HTTP请求以获取HTML内容。以下是一个简单的示例代码: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 htmlContent = await response.Content.ReadAsStringAsync();
// 输出HTML内容
Console.WriteLine(htmlContent);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
}
确保你的项目中引用了System.Net.Http命名空间。这段代码发送一个GET请求到指定的URL,并输出HTML内容。请注意,你可能需要处理网络异常和其他错误情况。
页:
[1]