使用 .NET Framework 编程-访问 Internet-使用 Internet 请求和响应类
1 using System;
2 using System.Net;
3 namespace WebRequest1
4 {
5 class Class1
6 {
7 [STAThread]
8 static void Main(string[] args)
9 {
10 Uri site=new Uri("http://www.baidu.com");
11 WebRequest wReq=WebRequest.Create(site);
12 ((HttpWebRequest)wReq).UserAgent="My Test";
13 WebResponse wResp=wReq.GetResponse();
14 DateTime updated=((HttpWebResponse)wResp).LastModified;
15 System.IO.Stream respStream=wResp.GetResponseStream();
16 System.IO.StreamReader reader=new System.IO.StreamReader
17 (respStream,System.Text.Encoding.GetEncoding("GB2312"));
18 string respHTML=reader.ReadToEnd();
19 Console.WriteLine(respHTML);
20 wResp.Close();
21 }
22 }
23 }
24
2 using System.Net;
3 namespace WebRequest1
4 {
5 class Class1
6 {
7 [STAThread]
8 static void Main(string[] args)
9 {
10 Uri site=new Uri("http://www.baidu.com");
11 WebRequest wReq=WebRequest.Create(site);
12 ((HttpWebRequest)wReq).UserAgent="My Test";
13 WebResponse wResp=wReq.GetResponse();
14 DateTime updated=((HttpWebResponse)wResp).LastModified;
15 System.IO.Stream respStream=wResp.GetResponseStream();
16 System.IO.StreamReader reader=new System.IO.StreamReader
17 (respStream,System.Text.Encoding.GetEncoding("GB2312"));
18 string respHTML=reader.ReadToEnd();
19 Console.WriteLine(respHTML);
20 wResp.Close();
21 }
22 }
23 }
24
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。