我正在编写一个程序,从其他网站下载html页面。我发现了一个问题,对于某个特定的网站,我无法获得完整的html代码。我只能得到部分内容。有此问题的服务器正在发送“传输-编码:分块”中的数据,恐怕这就是问题的原因。
这是服务器返回的头信息:
Transfer-Encoding: chunked
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Type: text/html; charset=UTF-8
Date: Sun, 11 Sep 2011 09:46:23 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Server: nginx/1.0.6这里是我的代码:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response;
CookieContainer cookie = new CookieContainer();
request.CookieContainer = cookie;
request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.UserAgent =
@"Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 FirePHP/0.6";
request.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
string html = string.Empty;
response = request.GetResponse() as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
html = reader.ReadToEnd();
}我只能获得部分html代码(我认为这是来自服务器的第一个块)。有人能帮忙吗?有解决办法吗?
谢谢!
发布于 2011-11-12 09:25:45
不能使用ReadToEnd读取块数据。您需要使用GetBytes直接从响应流读取。
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
do
{
count = resStream.Read(buf, 0, buf.Length);
if(count != 0)
{
sb.Append(Encoding.UTF8.GetString(buf,0,count)); // just hardcoding UTF8 here
}
}while (count > 0);
String html = sb.ToString();发布于 2011-11-12 09:07:24
如果我理解了你的要求,你可以一行行地读
string htmlLine = reader.ReadLine();https://stackoverflow.com/questions/7377581
复制相似问题