C#获取网页源码
WebClient
1
2
3
4
5
6
7
8
9
10
11 |
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( this .txtEncoder.Text)); strHTML = sr.ReadToEnd(); myStream.Close(); return
strHTML; } |
WebRequest
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
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( this .txtEncoder.Text)); string
strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return
strHTML; } |
HttpWebRequest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
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; } |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。