MSDN:WebClient提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法.
Demo(一):简单的请求请求一个页面内容
View Code
using System; using System.IO; using System.Net; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { String url = "http://www.baidu.com"; //先设定代理(在使用代理进行上网的时候用,如果没有使用代理则无需设置) WebProxy proxy = new WebProxy("192.168.19.9", 80); //创建 代理服务器设置对象 的实例 proxy.BypassProxyOnLocal = false; //代理服务器需要验证 proxy.Credentials = new NetworkCredential("jiaquanzhen", "abcd_123", "yellowpage"); //用户名密码 GlobalProxySelection.Select = proxy; //开始请求 WebClient client = new WebClient(); //设置请求的资源种类 client.Headers.Add("Accept", @"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); client.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5"); //获取网上资源的stream System.IO.Stream stream = client.OpenRead(url); //解码获取内容 System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8); String str = reader.ReadToEnd(); Console.WriteLine(str); } } }
Demo(二):异步请求获取数据
View Code
using System; using System.Web; using System.Web.UI; using System.IO; using System.Net; using System.Text; namespace WebApp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.btnBegin.Click += new EventHandler(btnBegin_Click); } void btnBegin_Click(object sender, EventArgs e) { //请求的url Uri uri = new Uri("http://www.baidu.com"); //初始化webclient,并设置头属性 WebClient client = new WebClient(); client.Headers.Add("Accept", @"image/gif,image/x-xbitmap,image/jpeg,application/x-shockwave-flash, appllication/vnd.ms-excel,application/vnd.ms-powerpoint,aplication/msword,*/*"); client.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5"); //进行异步读取 client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); client.OpenReadAsync(uri); } //回调函数 void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Stream stream = e.Result; StreamReader reader = new StreamReader(stream, Encoding.Default); String str = reader.ReadToEnd(); Response.Write(str); } } }