C#网络编程之WebClient
2015-06-18 11:34
531 查看
1.什么是WebClient?
源自MSDN:提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。
2.OpenRead() 为从具有String指定的URI的资源下载的数据打开一个可读的流。
需要先引用System.Net和System.IO.
3.OpenWrite() 打开一个流以将数据写入指定的资源.
4.DownloadFile() 将具有指定 URI 的资源下载到本地文件。
异步下载:
源自MSDN:提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。
2.OpenRead() 为从具有String指定的URI的资源下载的数据打开一个可读的流。
需要先引用System.Net和System.IO.
public static void GetPage(string uri) { WebClient wc = new WebClient(); Stream stream = wc.OpenRead(uri); //OpenRead的返回类型是Stream using (StreamReader sr = new StreamReader(stream)) { string line = ""; while ((line=sr.ReadLine())!=null) { Console.WriteLine(line); } } }
3.OpenWrite() 打开一个流以将数据写入指定的资源.
public void SendData(string uri, string content) { WebClient wc=new WebClient(); Stream stream = wc.OpenWrite(uri); using (StreamWriter sw = new StreamWriter(stream)) { sw.Write(content); } }
4.DownloadFile() 将具有指定 URI 的资源下载到本地文件。
WebClient wb = new WebClient(); wc.DownloadFile("http://www.xx.com", "xx.html");
异步下载:
WebClient wc = new WebClient(); wc.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage+ "% complete"); Task.Dealy(10000).ContinueWith(ant => wc.CancelAsync()); //如果超过限制时间,则取消下载 await wc.DownloadFileTaskAsync("http://www.xx.com", "xx.html"); // await 是C# 5.0中实现异步操作的关键字
相关文章推荐
- MQTT 开源代理mosquitto的网络层封装相当sucks
- Socket 通信原理(Android客户端和服务器以TCP&&UDP方式互通)
- android 网络编程--socket tcp/ip udp http之间的关系
- CDN的全称是Content Delivery Network,即内容分发网络
- (转) 网络流之最大流算法(EdmondsKarp)
- 在移动网络上创建更稳定的连接
- 关于网络的总结(二)
- 公网控制全攻略, 网络高手是这样炼成的
- socket属性设置函数总结
- android 解决 广播接收者监听网络变化会受到两次广播
- 快速Android开发系列网络篇之Android-Async-Http
- Linux网络编程——I/O复用函数之epoll
- 真的无语, 今天遇到一个奇葩的事情: http 会话劫持
- [Fiddler]如何让Fiddler可以抓取https的请求
- centos下Unix网络编程的源码的使用问题
- HTTP/1.1 100 Continue - I 服了 You
- 研究HttpClient的使用(黏贴复制的,仅作学习记录)
- http://www.highcharts.com/
- Chrome 下,重复使用 XMLHttpRequest进行Post数据时,遇到一个奇怪的问题
- MSXML2.ServerXMLHTTP & HTTPS & 证书过期 — msxml3.dll '80072f05'