首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 使用 POST 方法提交資料至遠端 URL 完整範例

     編輯:更多程式設計知識

Python 透過 urllib 與 urllib2(Python 2)或 urllib.request/urllib.parse(Python 3)即可實作 HTTP POST 請求。本文提供完整可執行範例並說明關鍵步驟。

Python 2 版本範例

import sys
import urllib2
import urllib

zipcode = "S2S 1R8"
url = 'https://www.yoursiteweb.com/getForecast'
data = urllib.urlencode([('query', zipcode)])

req = urllib2.Request(url)
fd = urllib2.urlopen(req, data)

while True:
    chunk = fd.read(1024)
    if not chunk:
        break
    sys.stdout.write(chunk)

Python 3 版本範例(推薦)

import sys
import urllib.request
import urllib.parse

zipcode = "S2S 1R8"
url = 'https://www.yoursiteweb.com/getForecast'
data = urllib.parse.urlencode({'query': zipcode}).encode('utf-8')

req = urllib.request.Request(url, data=data, method='POST')
with urllib.request.urlopen(req) as response:
    while True:
        chunk = response.read(1024)
        if not chunk:
            break
        sys.stdout.write(chunk.decode('utf-8'))

關鍵步驟解析

  1. 編碼資料:urlencode() 將字典/列表轉為 application/x-www-form-urlencoded 格式
  2. 建立 Request:指定 URL、資料、方法(POST)
  3. 發送請求:urlopen() 回傳類檔案物件
  4. 分塊讀取:避免大回應佔滿記憶體

進階:加入 Headers 與 JSON 資料

import json
import urllib.request

url = 'https://api.example.com/endpoint'
payload = {'name': 'John', 'age': 30}
data = json.dumps(payload).encode('utf-8')

req = urllib.request.Request(
    url,
    data=data,
    headers={
        'Content-Type': 'application/json',
        'User-Agent': 'Python-urllib/3.0'
    },
    method='POST'
)

with urllib.request.urlopen(req) as resp:
    result = json.loads(resp.read().decode('utf-8'))
    print(result)

推薦:使用 requests 套件(更簡潔)

# pip install requests
import requests

resp = requests.post(
    'https://api.example.com/endpoint',
    json={'name': 'John', 'age': 30},
    headers={'Authorization': 'Bearer token123'},
    timeout=10
)
print(resp.status_code)
print(resp.json())

錯誤處理最佳實踐

import urllib.request
import urllib.error

try:
    with urllib.request.urlopen(req, timeout=10) as resp:
        # 處理回應
        pass
except urllib.error.HTTPError as e:
    print(f"HTTP 錯誤: {e.code} {e.reason}")
except urllib.error.URLError as e:
    print(f"URL 錯誤: {e.reason}")
except Exception as e:
    print(f"其他錯誤: {e}")

總結

標準庫 urllib 功能完整但 API 較繁瑣;實務開發強烈建議使用 requests 套件,語法直觀、自動處理編碼/解碼、支援連線池與進階功能。若環境限制無法安裝第三方套件,urllib 仍是可靠備選。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved