如何使用httpx库实现类似curl --compressed的功能?
使用httpx实现
curl --compressed的功能 要实现和curl --compressed "http://example.com"完全一致的效果,关键是让httpx自动完成两件事:发送告知服务器支持压缩的请求头,以及在服务器返回压缩内容时自动解压,最终拿到原始数据。
基础用法(默认行为即可满足)
httpx的默认请求逻辑已经和curl --compressed对齐:
- 自动添加
Accept-Encoding: gzip, deflate, br请求头,告诉服务器客户端支持gzip、deflate和br三种压缩算法 - 当服务器返回带有
Content-Encoding头的压缩响应时,httpx会自动完成解压操作,你直接通过response.text(文本内容)或response.content(二进制内容)就能拿到原始未压缩的数据
示例代码:
import httpx # 发送请求,压缩协商和解压全自动化 response = httpx.get("http://example.com") # 输出解压后的文本内容 print(response.text) # 如果需要二进制原始数据,用response.content # print(response.content)
手动指定压缩算法(可选)
如果只需要支持特定的压缩算法,可以手动设置Accept-Encoding请求头,httpx依然会自动解压对应格式的响应:
import httpx # 只支持gzip和deflate压缩 headers = {"Accept-Encoding": "gzip, deflate"} response = httpx.get("http://example.com", headers=headers) # 自动解压符合要求的响应内容 print(response.text)
验证功能是否正常
你可以通过查看请求头和响应头,确认压缩协商和解压是否正常工作:
import httpx with httpx.Client() as client: response = client.get("http://example.com") # 查看发送的Accept-Encoding请求头 print("请求头 Accept-Encoding:", response.request.headers.get("Accept-Encoding")) # 查看服务器返回的Content-Encoding响应头(服务器支持压缩时才会存在) print("响应头 Content-Encoding:", response.headers.get("Content-Encoding")) # 对比原始压缩内容长度和解压后的长度(可选) print("解压后的内容长度:", len(response.content))
内容的提问来源于stack exchange,提问作者Ehud Lev
相关产品推荐
相关产品推荐

