获取指定网页HTML原码可使用 WebClient WebRequest HttpWebRequest 三种方式来实现。

当然也可使用webBrowse!在此就不研究webBrowse如何获取了。

WebClient

private string GetWebClient(string url)
{
    string strHTML = "";
    WebClient myWebClient = new WebClient();
    Stream myStream = myWebClient.OpenRead(url);
    StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));
    strHTML = sr.ReadToEnd();
    myStream.Close();
    return strHTML;
}

WebRequest

private string GetWebRequest(string url)
{
    Uri uri = new Uri(url);
    WebRequest myReq = WebRequest.Create(uri);
    WebResponse result = myReq.GetResponse();
    Stream receviceStream = result.GetResponseStream();
    StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
    string strHTML = readerOfStream.ReadToEnd();
    readerOfStream.Close();
    receviceStream.Close();
    result.Close();
    return strHTML;
}

HttpWebRequest

 

private string GetHttpWebRequest(string url)
{
    Uri uri = new Uri(url);
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
    myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
    myReq.Accept = "*/*";
    myReq.KeepAlive = true;
    myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
    HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
    Stream receviceStream = result.GetResponseStream();
    StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
    string strHTML = readerOfStream.ReadToEnd();
    readerOfStream.Close();
    receviceStream.Close();
    result.Close();
    return strHTML;
}

 

注意“utf-8”应与指定网页的编码对应。

1.本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2.分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3.不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4.本站提供的源码、模板、插件等其他资源,都不包含技术服务请大家谅解!
5.如有链接无法下载或失效,请联系管理员处理!
6.本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!