Loading

获取网页源码

 1      /// <summary>
 2         /// 获取对应url地址的源码
 3         /// </summary>
 4         /// <param name="url">传入的url地址</param>
 5         /// <returns></returns>
 6         public string GetWebContents(string url)
 7         {
 8             string webContent = "";
 9             Encoding encoding = Encoding.GetEncoding("GB2312");
10             try
11             {
12                 //申明一个HttpWebRequest请求
13                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
14                 //设置连接超时时间
15                 request.Timeout = 6000;
16                 request.Headers.Set("Pragma", "no-cache");
17 
18                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
19                 System.IO.Stream streamReceive = response.GetResponseStream();
20                 //获取对应url的编码
21                 if (response.CharacterSet.Contains("gbk"))
22                 {
23                     encoding = Encoding.GetEncoding("GB2312");
24                 }
25                 else if (response.CharacterSet.Contains("utf"))
26                 {
27                     encoding = Encoding.GetEncoding("UTF-8");
28                 }
29                 System.IO.StreamReader streamReader = new System.IO.StreamReader(streamReceive, encoding);
30                 //源码
31                 webContent = streamReader.ReadToEnd();
32                 //关闭流
33                 streamReceive.Close();
34                 streamReader.Close();
35             }
36             catch (Exception ex)
37             {
38                 MessageBox.Show(ex.Message);
39             }
40             return webContent;
41         }

 

posted @ 2013-01-15 00:29  jesn  阅读(238)  评论(0编辑  收藏  举报