用 WebClient 轻松实现文件下载上传、网页抓取
生活随笔
收集整理的這篇文章主要介紹了
用 WebClient 轻松实现文件下载上传、网页抓取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們知道用 WebRequest(HttpWebRequest、FtpWebRequest) 和 WebResponse(HttpWebResponse、FtpWebResponse)可以實現文件下載上傳、網頁抓取,可是用 WebClient 更輕松。
用 DownloadFile 下載網頁
using?(System.Net.WebClient client =?new?System.Net.WebClient()){
????client.DownloadFile("http://www.cftea.com/",?"C:\\foo.txt");
}
就這樣,http://www.cftea.com/?首頁就被保存到 C 盤下了。
用 DownloadData 或 OpenRead 抓取網頁
using?(System.Net.WebClient client =?new?System.Net.WebClient()){
????byte[] bytes = client.DownloadData("http://www.cftea.com/");
????string?str = (System.Text.Encoding.GetEncoding("gb2312").GetString(bytes);
}
我們將抓取來的網頁賦給變量 str,任由我們使用。也可以用 OpenRead 方法來獲取數據流。
using?(System.Net.WebClient client =?new?System.Net.WebClient()){
????using?(System.IO.Stream stream = client.OpenRead("http://www.cftea.com/"))
????{
????????using?(System.IO.StreamReader reader =?new?System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("gb2312")))
????????{
????????????string?str = reader.ReadToEnd();
????????????reader.Close();
????????}
????????stream.Close();
????}
}
用 UploadFile 上傳文件
相對于 DownloadData、OpenRead,WebClient 也具有 UploadData、OpenWrite 方法,但最常用的恐怕還是上傳文件,也就是用方法 UploadFile。
using?(System.Net.WebClient client =?new?System.Net.WebClient()){
????client.Credentials =?new?System.Net.NetworkCredential("用戶名",?"密碼");
????client.UploadFile("ftp://www.cftea.com/foo.txt",?"C:\\foo.txt");
}
注意 UploadFile 的第一個參數,要把上傳后形成的文件名加上去,也就是說這里不能是:ftp://www.cftea.com/。
用 UploadValues POST 數據
WebClient wb =?new?WebClient();NameValueCollection nvc =?new?NameValueCollection();
nvc.Add("param1", param1);
nvc.Add("param2", param2);
wb.UploadValues(url,?"post", nvc);
轉載于:https://www.cnblogs.com/jordan2009/archive/2012/10/18/2728888.html
總結
以上是生活随笔為你收集整理的用 WebClient 轻松实现文件下载上传、网页抓取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android开发中目前流行控件和知识点
- 下一篇: 测试用例设计--判定表