1. 程式人生 > 實用技巧 >http 協議中post請求資料格式

http 協議中post請求資料格式

這篇文章也有詳細說過:https://www.cnblogs.com/QiKa/p/12863127.html

HTTP 協議規定 POST 提交的資料必須放在訊息主體(entity-body)中

1、application/x-www-form-urlencoded 
#這應該是最常見的 POST 提交資料的方式了。瀏覽器的原生 form 表單,如果不設定 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交資料
如:Content-Type: application/x-www-form-urlencoded ; charset=utf-8

2、multipart/form-
data 使用表單上傳檔案時,必須讓 form 的 enctyped 等於這個值 如: POST http://www.example.com HTTP/1.1 Content-Type:multipart/form-data; boundary=---WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="text" title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content
-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/png 3、application/json application/json把它作為請求頭,用來告訴服務端,訊息主體是序列化後的 JSON 字串 4、text/xml 它是一種使用 HTTP 作為傳輸協議,XML 作為編碼方式的遠端呼叫規範 例項:------------------------------------------------------------ Python在呼叫外部http請求時,post請求進行傳 請求體body
1、application/x-www-form-urlencoded import urllib url = "http://www.example.com" body_value = {"package": "com.tencent.lian","version_code": "66" } body_value = urllib.urlencode(body_value) request = urllib2.Request(url, body_value) request.add_header(keys, headers[keys]) result = urllib2.urlopen(request ).read() 2、multipart/form-data 需要利用python的poster模組,安裝poster:pip install poster 程式碼: from poster.encode import multipart_encode from poster.streaminghttp import register_openers url = "http://www.baidu.com" body_value = {"package": "com.tencent.lian","version_code": "77" } register_openers() datagen, re_headers = multipart_encode(body_value) request = urllib2.Request(url, datagen, re_headers) # 如果有請求頭資料,則新增請求頭 request .add_header(keys, headers[keys]) result = urllib2.urlopen(request ).read() 3、application/json import json url = "http://www.baidu.com" body_value = {"package": "com.tencent.lian","version_code": "77" } register_openers() body_value = json.JSONEncoder().encode(_value)