Python 透過 urllib 與 urllib2(Python 2)或 urllib.request/urllib.parse(Python 3)即可實作 HTTP POST 請求。本文提供完整可執行範例並說明關鍵步驟。
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)
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'))
urlencode() 將字典/列表轉為 application/x-www-form-urlencoded 格式urlopen() 回傳類檔案物件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)
# 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 仍是可靠備選。