C# 发送Http请求 - WebClient类
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
公众号:hacker-thinking (一个程序员的思考)
独立博客:http://blog.coderzh.com
博客园博客将不再更新,请关注我的「微信公众号」或「独立博客」。
作为一个程序员,思考程序的每一行代码,思考生活的每一个细节,思考人生的每一种可能。
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。