基於本身踩過的坑,百度以後整理的,以備後期忘記以後,回憶回憶。json
http協議規定post傳輸數據必須放在消息體裏,但並未規定使用什麼編碼方式,常見的編碼方式有四種:瀏覽器
一、application/x-www-form-urlencoded 瀏覽器的原生 form 表單,若是不設置 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交數據。app
其傳參方式爲 key=value&key=value&key=value.. 也就意味着是以字符串形式傳輸 post
1 import requests
from urllib import parse 2 url='xxxx' 3 str = 'key={"k1": "v1","k2": "k2"}&k2=v2'
data = parse.quote(str, safe='=&') # safe 爲不轉碼字符,此例子爲 =和& 不作轉碼 4 headers = {'Content-Type': 'application/x-www-form-urlencoded'} #headers必需要傳 5 response = requests.post(url, data=data, headers=headers) 6 print(response.text)
二、multipart/form-data 使用表單上傳文件時,必須讓 form 的 enctyped 等於這個值編碼
其傳參方式爲 files = {'name': (<filename>, <file object>,<content type>, <per-part headers>)} 若是filename 和 content-Type不寫,那麼響應模擬post的數據就不會有兩者。url
1 data = { 2 'k1':(None, 'v1'), #filename設置爲None 3 'k2':(None, 'v2') # 4 } 5 response = requests.post(url, files=data) #默認headers以multipart/form-data編碼 6 print(response.text)
三、application/json 消息主體是序列化後的 JSON 字符串spa
其傳參是標準的json格式,不作贅述code
四、text/xml 是一種使用 HTTP 做爲傳輸協議,XML 做爲編碼方式的遠程調用規範orm
還沒有遇到,不作贅述xml