首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果返回的内容是传输的,如何从HttpWebResponse获得完整的内容-编码:分块?

如果返回的内容是传输的,如何从HttpWebResponse获得完整的内容-编码:分块?
EN

Stack Overflow用户
提问于 2011-09-11 10:22:09
回答 2查看 18K关注 0票数 15

我正在编写一个程序,从其他网站下载html页面。我发现了一个问题,对于某个特定的网站,我无法获得完整的html代码。我只能得到部分内容。有此问题的服务器正在发送“传输-编码:分块”中的数据,恐怕这就是问题的原因。

这是服务器返回的头信息:

代码语言:javascript
复制
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

这里是我的代码:

代码语言:javascript
复制
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代码(我认为这是来自服务器的第一个块)。有人能帮忙吗?有解决办法吗?

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2011-11-12 09:25:45

不能使用ReadToEnd读取块数据。您需要使用GetBytes直接从响应流读取。

代码语言:javascript
复制
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();
票数 9
EN

Stack Overflow用户

发布于 2011-11-12 09:07:24

如果我理解了你的要求,你可以一行行地读

代码语言:javascript
复制
string htmlLine = reader.ReadLine();
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7377581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档