使用urllib2确定内容长度

and*_*ton 0 python urllib2

我通过urllib2发出了一个带有以下标头的请求:

>>> dict(response.info())
{'expires': 'Wed, 31 Dec 1969 19:00:00 EST, Wed, 31 Dec 1969 19:00:00 EST', 'server': 'Apache-Coyote/1.1, Apache-Coyote/1.1', 'connection': 'close', 'pragma': 'No-cache, No-cache', 'cache-control': 'no-cache, no-cache', 'date': 'Thu, 19 Jan 2012 20:16:00 GMT', 'content-type': 'audio/mpeg'}
Run Code Online (Sandbox Code Playgroud)

据我了解,由于设置了“连接:关闭”,因此请求将继续流回,直到远程主机完成为止,因此未设置Content-Length。似乎我应该能够通过某种方式分析响应对象来确定内容的长度,但是我不知道该怎么做。有什么建议么?

Mar*_*rst 5

我认为您需要调用read()响应以将其读取为字符串,然后调用len()该字符串。

data = response.read()
length = len(data)
Run Code Online (Sandbox Code Playgroud)