惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
云风的 BLOG
云风的 BLOG
IT之家
IT之家
T
The Blog of Author Tim Ferriss
C
Check Point Blog
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
F
Fortinet All Blogs
D
DataBreaches.Net
The Register - Security
The Register - Security
L
LINUX DO - 最新话题
W
WeLiveSecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V2EX - 技术
V2EX - 技术
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
F
Full Disclosure
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
I
InfoQ
S
Secure Thoughts
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
AI
AI
Recent Announcements
Recent Announcements
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
SecWiki News
SecWiki News
Cisco Talos Blog
Cisco Talos Blog
H
Heimdal Security Blog
Y
Y Combinator Blog
N
News | PayPal Newsroom
P
Privacy International News Feed
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
D
Docker
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
A
About on SuperTechFans
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
T
Threat Research - Cisco Blogs

博客园 - peak

windows 服务器时间同步失败处理方法 利用批处理自动创建schtasks系统任务 在线调试利器Fiddler AutoResponse jquery跨域调用WCF Base-64 字符串中的无效字符 Ie7下鼠标滚轮失效 Android 笔记二(取得根目录权限) Android 笔记一 捕获asp.net ValidationSummary 控件消息。 - peak Sql Split 函数 Rss的浏览器之痛 兼容IE,Firefox 图片即时显示 asp.net 中插入flash - peak - 博客园 迷茫 windows service 之访问权限 windows Service 之调试过程 比尔盖兹在某个大学毕业典礼上的演讲中,对毕业生提出十一项极为睿智的人生建议 MSDN上关于泛型的例子 泛型
抓取网站编码信息及内容
peak · 2012-01-31 · via 博客园 - peak
     最近在编写一个读取网站内容的小东西,在网上一搜很多,但是在拿过来用时不太理想,有些内容读取还是出现乱码问题。于是我在loafinweb 这位兄弟代码的基础上做了一些小的调整,以达到个人需求,如有不对之处还请loafinweb 见谅。
1、获取编码片段:
把 string html = reader.ReadToEnd();
改写成
 while ((temp = reader.ReadLine()) != null)
{
htmlBuilder.Append(temp);
html = htmlBuilder.ToString();
if (html.IndexOf("charset", StringComparison.InvariantCultureIgnoreCase) > 0)
{
break;
}
}
这样对读取速度有所改进,只需要读取页面头部的编码部分即可,不需要读取整个页面。
2、添加对response.StatusCode == HttpStatusCode.MovedPermanently ||response.StatusCode==HttpStatusCode.Found情况的判断,递归获取编码。
(相关 Response.StatusCode的HTTP状态代码 请参考http://wenku.baidu.com/view/cc274309bb68a98271fefada.html)
如新浪www.sina.com,默认会跳到www.sina.com.cn
通过Fiddler可以抓取到相关的跳转过程

   

   

//获取编码
public static string getEncoding(string url)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
string temp = string.Empty;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 30000;
request.AllowAutoRedirect = false;
string html = "";
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
else
reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);

//此处不用ReadToEnd 方法,采用ReadLine 当读到charset时跳出。
//string html = reader.ReadToEnd();
StringBuilder htmlBuilder = new StringBuilder();
while ((temp = reader.ReadLine()) != null)
{
htmlBuilder.Append(temp);
html = htmlBuilder.ToString();
if (html.IndexOf("charset", StringComparison.InvariantCultureIgnoreCase) > 0)
{
break;
}
}

Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
if (reg_charset.IsMatch(html))
{
return reg_charset.Match(html).Groups["charset"].Value;
}
else if (response.CharacterSet != string.Empty)
{
return response.CharacterSet;
}
else
return Encoding.Default.BodyName;
}
else if (response.StatusCode == HttpStatusCode.MovedPermanently ||response.StatusCode==HttpStatusCode.Found)
{
//页面跳转返回301,如:www.sina.com
//重新读取跳转地址
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
else
reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
html = reader.ReadToEnd();
Regex reg_href = new Regex("<a[\\s]+href[\\s]*=[\\s]*\"([^<\"]+)\"");
if (reg_href.IsMatch(html))
{
var targetUrl=reg_href.Match(html).Groups[1].Value;
if (!IsURL(targetUrl))
{
url = url + targetUrl;
}
else
{
url = targetUrl;
}
return getEncoding(url);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close();

if (request != null)
request = null;
}
return Encoding.Default.BodyName;
}

3、获取网页内容时添加对gzip情况的判断,否则可能出现乱码如www.sohu.com
//获取网页字符根据url  
public static string getHtml(string url)
{
try
{
string str = "";
Encoding en = Encoding.GetEncoding(getEncoding(url));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Set("Pragma", "no-cache");
request.Timeout = 30000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
{
//此处不要用StreamReader 直接读取,需要判断gzip情况
//否则可能出现乱码现象,如www.sohu.com
//Stream strM = response.GetResponseStream();
//StreamReader sr = new StreamReader(strM, en);
StreamReader sr;
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
sr = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress),en);
else
sr = new StreamReader(response.GetResponseStream(), en);
str = sr.ReadToEnd();
//strM.Close();
sr.Close();
}
return str;
}
catch
{
return String.Empty;
}
}
代码下载
参考:http://www.cnblogs.com/clc2008/archive/2011/09/13/2174284.html