码迷,mamicode.com
首页 > Windows程序 > 详细

C# 取得网址源码

时间:2015-12-03 14:02:10      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

HttpWebRequest wwb = (HttpWebRequest)WebRequest.Create(url);
wwb.UserAgent = "Mozilla/5.0";//用户代理;与浏览器相关;没有的话,可能会导致GetResponse()
wwb.ContentType = "text/html; charset=UTF-8";
wwb.Method = "GET";
WebResponse wwebRes = null;// (HttpWebResponse)wwb.GetResponse();
Stream wwebStream = null;
StreamReader sssr = null;// new StreamReader(wwebRes.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
//string sstrHtml;
StringBuilder sb = new StringBuilder();
try
{
wwebRes = (HttpWebResponse)wwb.GetResponse();
}
catch (WebException ex)
{
//wwebRes = (HttpWebResponse)ex.Response;//错误信息
return "";
}
finally
{
//及时释放资源
if (wwebRes != null)
{
wwebStream = wwebRes.GetResponseStream();
sssr = new StreamReader(wwebRes.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
//获得网页源码
string str1 = null;
while ((str1 = sssr.ReadLine()) != null)
{
sb.Append(str1);
}
// sstrHtml = sssr.ReadToEnd();
wwebStream.Close();
sssr.Close();
wwebRes.Close();
wwb.Abort();
}
}

C# 取得网址源码

标签:

原文地址:http://www.cnblogs.com/sulong/p/5015546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!