连接到同一主机时,Python请求和urllib2会获得不同的标头

时间:2017-01-14 07:10:54

标签: python python-requests urllib2

我们有一台服务器提供.txt文件,基本上一些日志文件会随着时间的推移而增长。当我使用urllib2GET发送到服务器r = urllib2.urlopen('http://example.com')时,响应的标头将为:

Date: XXX
Server: Apache
Last-Modified: XXX
Accept-Ranges: bytes
Content-Length: 12345678
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

如果r = requests.get('http://example.com')

Content-Encoding: gzip
Accept-Ranges: bytes
Vary: Accept-Encoding
Keep-alive: timeout=5, max=128
Last-Modified: XXX
Connection: Keep-Alive
ETag: xxxxxxxxx
Content-Type: text/plain

第二个响应与使用chrome开发工具获得的结果相同。那两个为什么不同呢?我需要Content-Length标头来确定每次需要下载多少字节,因为文件可能会变得非常大。

编辑: 使用httpbin.org/get进行测试:

urllib2回复:

{u'args': {},
 u'headers': {u'Accept-Encoding': u'identity',
              u'Host': u'httpbin.org',
              u'User-Agent': u'Python-urllib/2.7'},
 u'origin': u'ip',
 u'url': u'http://httpbin.org/get'}

响应标题:

Server: nginx
Date: Sat, 14 Jan 2017 07:41:16 GMT
Content-Type: application/json
Content-Length: 207
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

请求回复:

{u'args': {},
 u'headers': {u'Accept': u'*/*',
              u'Accept-Encoding': u'gzip, deflate',
              u'Host': u'httpbin.org',
              u'User-Agent': u'python-requests/2.11.1'},
 u'origin': u'ip',
 u'url': u'http://httpbin.org/get'}

响应标题:

Server : nginx
Date : Sat, 14 Jan 2017 07:42:39 GMT
Content-Type : application/json
Content-Length : 239
Connection : keep-alive
Access-Control-Allow-Origin : *
Access-Control-Allow-Credentials : true

1 个答案:

答案 0 :(得分:1)

来自Lukasa的github:

  

响应不同,因为请求表明它支持   gzip编码的主体,通过发送Accept-Encoding:gzip,deflate   标题字段。 urllib2没有。您将找到是否添加了该标题   你的urllib2请求你得到了新的行为。

     

显然,在这种情况下,服务器正在动态地解压缩   响应。这意味着它不知道响应的时间长短,   所以它使用分块传输编码发送。

     

如果你真的必须得到Content-Length标题,那么你应该添加   您的请求请求的以下标头:{' Accept-Encoding':   '身份'}