引用:
using System.IO;
using System.Net;
代码:
////// Get网址,返回网页源码 /// /// 需要Get的网址。例:http://www.baidu.com /// 目标网页的编码集。便:utf-8,gb2312 ///public string GetWeb(string webUrl, string charset) { WebRequest request = WebRequest.Create(webUrl); WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s, Encoding.GetEncoding(charset));//编码格式 string webHtml = sr.ReadToEnd();//返回Html sr.Dispose(); sr.Close(); s.Dispose(); s.Close(); return webHtml; }
调用:
MessageBox.Show(GetWeb(", "gb2312"));
MessageBox.Show(GetWeb(", "utf-8"));
方法二:
////// Get网址,返回网页源码 /// /// 需要Get的网址。例:http://www.baidu.com /// 目标网页的编码集。便:utf-8,gb2312 ////// 示例 /// MessageBox.Show(GetHttpWebRequest("http://www.baidu.com", "gb2312")); /// MessageBox.Show(GetHttpWebRequest("http://cn.yahoo.com/index.html", "utf-8")); public string GetHttpWebRequest(string url, string charset) { 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(charset)); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; }