Accept-Encoding学习

今天使用python的 urlilib2访问天气接口的时候一直乱码,原因是内容被gzip压缩了,对内容解压缩即可。python2的urllib2读取网页乱码

问题是解决了,可是为什么访问这个接口会因为gzip压缩乱码,而访问百度等其他网站不会乱码。
之前以为是urllib2在read前自己判断了meta的一些内容,然后做了gzip解压缩。查看源码后,未找到该操作。
转而把注意力放到gzip本身上,gzip除了在Response的Header上有出现,在Request的Header上也有。

Response Headers
Content-Encoding:gzip

Request Headers
Accept-Encoding:gzip, deflate, sdch, br

查询得知:

当客户端发送Accept-Encoding:gzip这个request header,服务器即认为其能接受gzip压缩,就响应一个Content-Encoding:gzip,并发送压缩内容;假如客户端没有发送 Accept-Encoding,那么服务器就把源代码老老实实地打印出去。
强制返回gzip压缩的内容

由于之前未加header,百度直接返回了未压缩的内容。于是这里Accept-Encoding加上gzip

import urllib2
import gzip
import StringIO
headers={'Accept-Encoding':'gzip'}
url='http://www.baidu.com'
request = urllib2.Request(url,headers=headers)
res = urllib2.urlopen(request)
s = res.read()
print(s)
print('----------------------')
s=StringIO.StringIO(s)
gzipper=gzip.GzipFile(fileobj=s)
ungzipStr=gzipper.read()
print(ungzipStr)

解压缩后内容才是正常的。
这里写图片描述

可见,当客户端发送Accept-Encoding:gzip这个request header的时候,服务器会返回gzip压缩后的内容。之前的天气预报接口不过是强制返回了gzip的内容而已。

还有很多要学习的呀。

参考资料:

urllib2.urlopen处理gzip数据

http压缩 Content-Encoding: gzip

HTTP 协议中的 Content-Encoding

强制返回gzip压缩的内容

其他资料:
transfer-encoding:chunked的含义

http协议中content-length 以及chunked编码分析

原文地址:https://www.cnblogs.com/thewindkee/p/12873221.html