下载

 1 using System;
 2 using System.Text;
 3 using System.Text.RegularExpressions;
 4 using System.IO;
 5 using System.Net;
 6  
 7 class DownloadStringTest
 8 {
 9  
10     static void Main(string[] args)
11     {
12         string url = "http://www.baidu.com";
13         if (args.Length != 0) url = args[0];
14         string str = DownloadString(url);
15         Console.WriteLine(str);
16     }
17  
18     public static string DownloadString(string url)
19     {
20         try
21         {
22             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
23             request.Credentials = CredentialCache.DefaultCredentials;
24             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
25  
26             Stream responseStream = response.GetResponseStream();
27             Encoding encoding = Encoding.UTF8; //Encoding.Default;
28             StreamReader reader = new StreamReader(responseStream, encoding);
29             string str = reader.ReadToEnd();
30             reader.Close();
31             responseStream.Close();
32             response.Close();
33             return str;
34         }
35         catch (UriFormatException exception)
36         {
37             Console.WriteLine(exception.Message.ToString());
38             Console.WriteLine("Invalid URL format.  Please use http://www.yoursite.com");
39         }
40         catch (WebException exception2)
41         {
42             Console.WriteLine(exception2.Message.ToString());
43         }
44         return "";
45     }
46  
47 }

 

posted @ 2018-01-22 09:26  奔跑的蒲公英  阅读(137)  评论(0编辑  收藏  举报