涵蓋 urllib、urllib2、httplib 三模組發送 GET/POST 請求、處理回應標頭/內容、CGI 測試端點完整實作,並對比三模組層級差異。
#!/usr/bin/env python
import cgi
print("Content-type: text/html\n")
form = cgi.FieldStorage()
if form.getvalue("ServiceCode"):
print(f" Hello {form.getvalue('ServiceCode')}
")
else:
print(" Error! Please enter first name.
")
# 方法一:urllib2
import urllib2
url = "https://host/cgi-bin/test.py?ServiceCode=aaaa"
req = urllib2.Request(url)
print(urllib2.urlopen(req).read())
# 方法二:httplib (底層)
import httplib
conn = httplib.HTTPConnection("host")
conn.request("GET", "/cgi-bin/test.py?ServiceCode=aaaa")
print(conn.getresponse().read())
conn.close()
# 方法一:urllib2
import urllib, urllib2
data = urllib.urlencode({'ServiceCode': 'aaaa', 'b': 'bbbbb'})
req = urllib2.Request("https://host/cgi-bin/test.py", data)
print(urllib2.urlopen(req).read())
# 方法二:httplib
import urllib, httplib
data = urllib.urlencode({'ServiceCode': 'aaaa', 'b': 'bbbbb'})
headers = {"Host": "host", "Content-Type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection("host")
conn.request("POST", "/cgi-bin/test.py", body=data, headers=headers)
print(conn.getresponse().read())
conn.close()
read([amt]):讀取回應主體 (bytes)。getheader(name, default):取單一標頭。getheaders():回傳列表 [(name, value), ...]。status / reason:狀態碼與原因短語。httplib (最底層 HTTP/HTTPS 協議實作) ↑ 封裝 urllib (URL 開啟、編碼、代理、認證) ↑ 封裝 urllib2 (Request/Response 物件、Handler 鏈、Cookie、重導向) ← Python 2 主力
Python 3 整合為 urllib.request/urllib.parse/urllib.error,httplib 改名 http.client。
requests 或 httpx (支援 async)。urllib.request 為主力,http.client 僅用於精細控制 (如自定義連線池、CONNECT 隧道)。timeout、檢查 status、處理編碼、關閉連線 (或用 with)。