如何使用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 分享