WebClient位于System.Net命名空间下,通过这个类可以方便的创建Http请求并获取返回内容。
一、用法1 - DownloadData
string uri = "http://coderzh.cnblogs.com";
WebClient wc = new WebClient();
Console.WriteLine("Sending an HTTP GET request to " + uri);
byte[] bResponse = wc.DownloadData(uri);
string strResponse = Encoding.ASCII.GetString(bResponse);
Console.WriteLine("HTTP response is: ");
Console.WriteLine(strResponse);
WebClient wc = new WebClient();
Console.WriteLine("Sending an HTTP GET request to " + uri);
byte[] bResponse = wc.DownloadData(uri);
string strResponse = Encoding.ASCII.GetString(bResponse);
Console.WriteLine("HTTP response is: ");
Console.WriteLine(strResponse);
二、用法2 - OpenRead
string uri = " http://coderzh.cnblogs.com";
WebClient wc = new WebClient();
Console.WriteLine("Sending an HTTP GET request to " + uri);
Stream st = wc.OpenRead(uri);
StreamReader sr = new StreamReader(st);
string res = sr.ReadToEnd();
sr.Close();
st.Close();
Console.WriteLine("HTTP Response is ");
Console.WriteLine(res);
WebClient wc = new WebClient();
Console.WriteLine("Sending an HTTP GET request to " + uri);
Stream st = wc.OpenRead(uri);
StreamReader sr = new StreamReader(st);
string res = sr.ReadToEnd();
sr.Close();
st.Close();
Console.WriteLine("HTTP Response is ");
Console.WriteLine(res);
本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/11/25/1340794.html,如需转载请自行联系原作者