Python处理Gzip/Deflate响应

74 阅读1分钟

huake_00219_.jpg在Web开发中,服务器经常使用Gzip或Deflate压缩HTTP响应以减少传输数据量。Python的HTTP客户端库提供了多种方式来处理这些压缩响应,本文将介绍主流方法及最佳实践。

requests库****

requests库默认会自动处理压缩响应(支持gzip、deflate和brotli):

python

 import requests
  
 response = requests.get('example.com', headers={'Accept-Encoding': 'gzip, deflate'})
 print(response.text) # 自动解压后的内容
 print(response.headers['Content-Encoding']) # 查看原始编码

urllib3****

urllib3同样支持自动解压,但需注意连接池配置:

python

 import urllib3
  
 http = urllib3.PoolManager()
 response = http.request('GET', 'example.com')
 print(response.data.decode('utf-8')) # 自动解压后的数据

HTTP响应,在数据传输效率和处理灵活性之间取得最佳平衡。