python httpx庫實現HTTP/2 POST請求
本文演示如何使用Python的httpx庫發送HTTP/2 POST請求,模擬cURL命令的功能。
場景描述
假設我們需要用curl命令發送一個HTTP/2 POST請求:
curl --http2-prior-knowledge -X POST http://127.0.0.1:1313 -d 'ww$$go'
我們希望用httpx庫達到同樣的效果。直接使用httpx的簡單方法可能無法滿足需求。
解決方法
要正確使用httpx發送HTTP/2 POST請求,需要仔細設置請求頭和數據格式。以下代碼提供了解決方案:
立即學習“Python免費學習筆記(深入)”;
import httpx url = "http://127.0.0.1:1313" data = "ww$$go" headers = { "Content-Type": "application/x-www-form-urlencoded", # 正確設置Content-Type } with httpx.Client(http2=True) as client: response = client.post(url, data=data, headers=headers) print(f"狀態碼: {response.status_code}") print("響應內容:") print(response.text)
此代碼創建了一個HTTP/2客戶端,并設置了URL、數據和請求頭。關鍵在于設置Content-Type為application/x-www-form-urlencoded,確保數據以正確的格式發送。 這樣就能用httpx庫成功模擬curl命令的HTTP/2 POST請求。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END