如何使用Python的httpx库发送与curl命令等效的HTTP/2 POST请求?

如何使用Python的httpx库发送与curl命令等效的HTTP/2 POST请求?

python httpx库模拟HTTP/2 POST请求

本文演示如何使用Python的httpx库发送与cURL命令等效的HTTP/2 POST请求。假设您已熟悉curl命令,并希望将其功能迁移到httpx库。

您希望模拟的curl命令如下:

curl --http2-prior-knowledge -x post http://127.0.0.1:1313 -d 'ww$$go'

直接使用httpx库的简单尝试可能失败,例如:

with httpx.Client(http2=True, verify=False) as client:     res = client.post('http://127.0.0.1:1313', data=b'dtest')     print("res", res)

关键在于设置正确的Content-Type请求头。以下代码提供了正确的httpx实现:

立即学习Python免费学习笔记(深入)”;

import httpx  url = "http://127.0.0.1:1313" data = "ww$$go" headers = {     "Content-Type": "application/x-www-form-urlencoded" }  with httpx.Client(http2=True) as client:     response = client.post(url, data=data, headers=headers)  print(f"状态码: {response.status_code}") print("响应内容:") print(response.text)

这段代码通过设置Content-Type为”application/x-www-form-urlencoded”,准确地模拟了curl命令的POST请求,并使用HTTP/2协议进行传输。 确保您的环境已正确安装httpx库 (pip install httpx) 并且目标服务器支持HTTP/2。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享