C#下载html页面

csharp

浏览数:141

2019-1-7

 public string GetHtml(string url)
{
    string html = "";

    //创建 http 连接获取数据
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        //是否获取到数据
        if (response.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("获取数据异常,状态码:" + response.StatusCode);
        }

        //读取数据
        using (Stream inputStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(inputStream))
        {
            html = reader.ReadToEnd();
        }
    }

    return html;
}