
本文演示如何使用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。
以上就是如何使用Python的httpx库发送与curl命令等效的HTTP/2 POST请求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号