【发布时间】:2015-04-15 07:00:14
【问题描述】:
目前,我正在研究接收 tcp 流并通过 python 分析 HTTP 数据。我已经在here 了解了如何解码分块数据。我的问题是:当我持有整个 HTTP 响应并开始对其进行解码时,但前缀块大小比实际大小要小得多。我将在下面显示:
这是我收到的纯数据:
b'000096F6\r\n<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://opengraphprotocol.org/schema/ fb: http://www.facebook.com/2010/fbml d: http://dictionary.com/2011/dml">\n<head>\n<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>\n<base href="http://dictionary.reference.com/">\n<title>Search | Define Search at Dictionary.com</title>\n<script.....(more data)
你可以看到前缀大小是 (hex)96F6 = 38646 (bytes)
但是如果我用这个算法分割数据:
encoded = row_data;
new_data = ""
while encoded != '':
off = int(encoded[:encoded.index('\r\n')], 16)
if off == 0:
break
encoded = encoded[encoded.index('\r\n') + 2:]
new_data = new_data.__add__(encoded[:off])
encoded = encoded[off + 2:]
return new_data
我只能得到两个损坏的组:
(more data).....<div class="dot dot-left dot-bottom "></
和
v>
<div class="language-name oneClick-disabled">.....(more data)
所以它通过我一个异常,无法在下一个循环中关闭。 当我仔细检查响应体时,我得到 len(data) 是 78543,len(data.decode()) 是 78503,整个响应只有一个块!
然后我尝试了很多网络设置,他们都遇到了这个问题。
所以,我的问题是:我怎么了?如何正确解码此类数据? 感谢可以提供帮助的人!
【问题讨论】:
标签: python http chunked-encoding