python request.post異常

西北逍遥發表於2024-03-16

python post報錯 退出 Failed to establish a new connection

import requests
from requests.exceptions import RequestException

# 設定URL和請求資料
url = 'http://example.com/api/resource'
data = {'key1': 'value1', 'key2': 'value2'}

# 嘗試傳送POST請求
try:
    response = requests.post(url, json=data, timeout=10)  # 設定超時時間
    response.raise_for_status()  # 如果請求失敗,會丟擲HTTPError異常
    print(response.json())  # 假設伺服器返回JSON響應
except RequestException as e:
    # 處理所有requests庫丟擲的異常,包括連線錯誤
    print(f"An error occurred while trying to send the POST request: {e}")
    # 在這裡你可以嘗試重試邏輯,例如:
    # 重試次數和間隔可以根據實際需求調整
    retries = 5
    retry_interval = 5  # seconds
    for _ in range(retries):
        try:
            response = requests.post(url, json=data, timeout=10)
            response.raise_for_status()
            print(response.json())
            break  # 如果請求成功,則跳出迴圈
        except RequestException as e:
            print(f"Retrying after {retry_interval} seconds...")
            time.sleep(retry_interval)
    else:
        print("Max retries exceeded. Giving up.")

#########################

相關文章