网络信息获取代码2------ 慕课第10 北大唐大壮

 1 using System;
 2 using System.Text;
 3 using System.Text.RegularExpressions;//正则表达式
 4 using System.IO;
 5 using System.Net;
 6 
 7 namespace _2
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string url = @"http://www.baidu.com";
14             if (args.Length != 0) url = args[0];
15             string str = DownloadString(url);
16             Console.WriteLine(str);
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 https://www.yousitr.com");
39             }
40             catch(WebException exception2)
41             {
42                 Console.WriteLine(exception2.Message.ToString());
43             }
44             return "";
45         }
46     }
47 }
原文地址:https://www.cnblogs.com/gdf456/p/9492026.html