Python開發【模組】:Requests(二),pythonrequests
Requests模組常見的4中post請求
HTTP 協議規定 POST 提交的資料必須放在訊息主體(entity-body)中,但協議並沒有規定資料必須使用什麼編碼方式。常見的四種編碼方式如下:
1、application/x-www-form-urlencoded
這應該是最常見的 POST 提交資料的方式了。瀏覽器的原生 form 表單,如果不設定 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交資料。請求類似於下面這樣:
import requestsimport jsonCONFIG = { 'url': 'http://192.168.90.10:8888/', 'headers': {'Content-Type': 'application/x-www-form-urlencoded'}}data = {'content': 'hello', 'digital': '0', 'punctuate': '1', 'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, data=data,headers=headers,timeout=1)print(response.content)
用wirshark進行抓包,分析請求的資料格式
追蹤http資料流,可以看到請求的資料進行了這樣的拼接content=hello&engModel=2&punctuate=1&digital=0
2、multipart/form-data
這又是一個常見的 POST 資料提交的方式。我們使用表單上傳檔案時,必須讓 form 的 enctyped 等於這個值,下面是樣本
import requestsimport jsonCONFIG = { 'url': 'http://192.168.90.10:8888/', 'headers': {'Content-Type': 'multipart/form-data '}}data = {'content': 'hello', 'digital': '0', 'punctuate': '1', 'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, files=data,headers=headers,timeout=1)print(response.content)
用wirshark進行抓包,分析請求的資料格式
追蹤http資料流,可以看到請求的資料
3、application/json
application/json 這個 Content-Type 作為回應標頭大家肯定不陌生。實際上,現在越來越多的人把它作為要求標頭,用來告訴服務端訊息主體是序列化後的 JSON 字串。由於 JSON 規範的流行,除了低版本 IE 之外的各大瀏覽器都原生支援 JSON.stringify,服務端語言也都有處理 JSON 的函數,使用 JSON 不會遇上什麼麻煩。
import requestsimport jsonCONFIG = { 'url': 'http://192.168.90.10:8888/', 'headers': {'Content-Type': 'application/json'}}data = {'content': 'hello', 'digital': '0', 'punctuate': '1', 'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, data=json.dumps(data),headers=headers,timeout=1)print(response.content)
用wirshark進行抓包,分析請求的資料格式
追蹤http資料流,可以看到請求的資料
4、text/xml
它是一種使用 HTTP 作為傳輸協議,XML 作為編碼方式的遠程調用規範。