利用.NET框架提供的 WebClient类 和 WebRequest类,我们可以很轻易地得到给定URL地址的源代码
测试地址: http://dotnet.aspx.cc/Exam/GetPageHtml.aspx
代码片段:
测试地址: http://dotnet.aspx.cc/Exam/GetPageHtml.aspx
代码片段:
1 private void WebClientButton_Click(object sender, System.EventArgs e)
2 {
3 PageUrl = UrlText.Text;
4 WebClient wc = new WebClient();
5 wc.Credentials = CredentialCache.DefaultCredentials;
6
7 ///方法一:
8 Byte[] pageData = wc.DownloadData(PageUrl);
9 ContentHtml.Text = Encoding.Default.GetString(pageData);
10
11 /// 方法二:
12 /// ***************代码开始**********
13 /// Stream resStream = wc.OpenRead(PageUrl);
14 /// StreamReader sr = new StreamReader(resStream,System.Text.Encoding.Default);
15 /// ContentHtml.Text = sr.ReadToEnd();
16 /// resStream.Close();
17 /// **************代码结束********
18 ///
19 wc.Dispose();
20 }
21
22 private void WebRequestButton_Click(object sender, System.EventArgs e)
23 {
24 PageUrl = UrlText.Text;
25 WebRequest request = WebRequest.Create(PageUrl);
26 WebResponse response = request.GetResponse();
27 Stream resStream = response.GetResponseStream();
28 StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
29 ContentHtml.Text = sr.ReadToEnd();
30 resStream.Close();
31 sr.Close();
32 }
33
2 {
3 PageUrl = UrlText.Text;
4 WebClient wc = new WebClient();
5 wc.Credentials = CredentialCache.DefaultCredentials;
6
7 ///方法一:
8 Byte[] pageData = wc.DownloadData(PageUrl);
9 ContentHtml.Text = Encoding.Default.GetString(pageData);
10
11 /// 方法二:
12 /// ***************代码开始**********
13 /// Stream resStream = wc.OpenRead(PageUrl);
14 /// StreamReader sr = new StreamReader(resStream,System.Text.Encoding.Default);
15 /// ContentHtml.Text = sr.ReadToEnd();
16 /// resStream.Close();
17 /// **************代码结束********
18 ///
19 wc.Dispose();
20 }
21
22 private void WebRequestButton_Click(object sender, System.EventArgs e)
23 {
24 PageUrl = UrlText.Text;
25 WebRequest request = WebRequest.Create(PageUrl);
26 WebResponse response = request.GetResponse();
27 Stream resStream = response.GetResponseStream();
28 StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
29 ContentHtml.Text = sr.ReadToEnd();
30 resStream.Close();
31 sr.Close();
32 }
33