C# 发送Http请求 - WebClient类
下载文件:
1 WebClient client = new WebClient(); 2 3 //第一种 4 5 string URLAddress = @"https://files.cnblogs.com/x4646/tree.zip"; 6 7 string receivePath=@"C:\"; 8 9 client.DownloadFile(URLAddress, receivePath + System.IO.Path.GetFileName(URLAddress)); 10 11 //就OK了。 12 13 //第二种 14 15 Stream str = client.OpenRead(URLAddress); 16 StreamReader reader = new StreamReader(str); 17 byte[] mbyte = new byte[1000000]; 18 int allmybyte = (int)mbyte.Length; 19 int startmbyte = 0; 20 21 while (allmybyte > 0) 22 { 23 24 int m = str.Read(mbyte, startmbyte, allmybyte); 25 if (m == 0) 26 break; 27 28 startmbyte += m; 29 allmybyte -= m; 30 } 31 32 reader.Dispose(); 33 str.Dispose(); 34 35 string path = receivePath + System.IO.Path.GetFileName(URLAddress); 36 FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); 37 fstr.Write(mbyte, 0, startmbyte); 38 fstr.Flush(); 39 fstr.Close();
WebClient位于System.Net命名空间下,通过这个类可以方便的创建Http请求并获取返回内容。
一、用法1 - DownloadData
1 string uri = "http://coderzh.cnblogs.com"; 2 WebClient wc = new WebClient(); 3 Console.WriteLine("Sending an HTTP GET request to " + uri); 4 byte[] bResponse = wc.DownloadData(uri); 5 string strResponse = Encoding.ASCII.GetString(bResponse); 6 Console.WriteLine("HTTP response is: "); 7 Console.WriteLine(strResponse);
二、用法2 - OpenRead
1 string uri = " http://coderzh.cnblogs.com"; 2 WebClient wc = new WebClient(); 3 Console.WriteLine("Sending an HTTP GET request to " + uri); 4 Stream st = wc.OpenRead(uri); 5 StreamReader sr = new StreamReader(st); 6 string res = sr.ReadToEnd(); 7 sr.Close(); 8 st.Close(); 9 Console.WriteLine("HTTP Response is "); 10 Console.WriteLine(res);