服務端通常是根據請求頭(headers)中的 Content-Type 字段來獲知請求中的消息主體是用何種方式編碼,再對主體進行解析。所以說到 POST 提交數據方案,包含了 Content-Type 和消息主體編碼方式兩部分。
application/x-www-form-urlencoded
最基本的form表單結構,用於傳遞字符參數的鍵值對,請求結構如下
POST HTTP/1.1
Host: www.demo.com
Cache-Control: no-cache
Postman-Token: 81d7b315-d4be-8ee8-1237-04f3976de032
Content-Type: application/x-www-form-urlencoded
key=value&testKey=testValue
請求頭中的Content-Type設置爲application/x-www-form-urlencoded; 提交的的數據,請求body中按照 key1=value1&key2=value2 進行編碼,key和value都要進行urlEncode;
multipart/form-data
這是上傳文件時,最常見的數據提交方式,看一下請求結構
POST HTTP/1.1
Host: www.demo.com
Cache-Control: no-cache
Postman-Token: 679d816d-8757-14fd-57f2-fbc2518dddd9
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="key"
value
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="testKey"
testValue
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="imgFile"; filename="no-file"
Content-Type: application/octet-stream
<data in here>
------WebKitFormBoundary7MA4YWxkTrZu0gW--
首先請求頭中的Content-Type 是multipart/form-data; 並且會隨機生成一個boundary, 用於區分請求body中的各個數據; 每個數據以 --boundary 開始, 緊接着換行,下面是內容描述信息, 接着換2行, 接着是數據; 然後以 --boundary-- 結尾, 最後換行;
文本數據和文件,圖片的內容描述是不相同的
文本參數:
Content-Disposition: form-data; name="key"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
文件參數:
Content-Disposition: form-data; name="imgFile"; filename="no-file"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
每個換行都是 \r\n ;
application/json
text/xml
text/plain
請求頭的Content-Type設置爲這幾個也很常見, 不過一般是在web前端開發中,請求body沒有固定結構, 直接傳輸對應數據的數據流, 不必和上面2種樣, 還要用固定的結構包起來, 只不過數據對應的是json, xml, 文本;
作者:Simon_z
鏈接:https://www.jianshu.com/p/4f9e79eb0163
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯繫作者獲得授權並註明出處。