很多人在使用 POST 的時候其實是不知道 <b>Content-Type</b> 的,以至于在看一些官方的 API 的時候懵逼了,完全沒見過也不知道這個是什么 POST 啊。

黑人問號.jpg
那么我們今天,就來學(xué)習(xí)一下,<b>POST</b> 方式下 <b>Content-Type</b> 的幾種方式。
本文后端以 <b>PHP</b> 為例。(以后也都是)
一、application/x-www-form-urlencoded
<b>application/x-www-form-urlencoded</b> 是最常用的方式,普通的表單提交、js異步請求都默認(rèn)都是通過這種方式。 用$_POST即可獲取數(shù)據(jù)。
報文
POST HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
name=anonymous66&sex=man
服務(wù)端代碼
var_dump($_POST);
輸出
array(2) {
["name"] => string(6) "anonymous66"
["sex"] => string(3) "man"
}
二、multipart/form-data
<b>multipart/form-data</b> 用在有上傳文件的時候。$_FILE 獲取文件內(nèi)容,$_POST 獲取數(shù)據(jù)。
報文
POST HTTP/1.1
Host: 127.0.0.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="name"
anonymous66
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="sex"
man
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="avater"; filename=""
Content-Type:
----WebKitFormBoundary7MA4YWxkTrZu0gW
服務(wù)端代碼
var_dump($_POST);
var_dump($_FILES);
輸出
array(2) {
["name"] => string(6) "anonymous66"
["sex"] => string(3) "man"
}
array(1) {
["avater"]=> array(5) {
["name"] => string(36) "0CD0A5235EDCDAAB4AFE05B25695E696.png"
["type"] => string(9) "image/png"
["tmp_name"] => string(45) "/Applications/XAMPP/xamppfiles/temp/phpeFfc9e"
["error"] => int(0)
["size"] => int(9485)
}
}
三、raw
raw 可以上傳 json、xml、文本 等等。用 php://input 獲得內(nèi)容。
以下是 raw 具體的方式:
text/plain
text/html
text/xml
application/json
application/xml
application/javascirpt
報文
POST HTTP/1.1
Host: 127.0.0.1
Content-Type: application/json
{
"user": "anonymous66",
"sex": "man"
}
服務(wù)端代碼
var_dump( file_get_contents('php://input') );
輸出
string(48) "{ "user": "anonymous66", "sex": "man"}"
四、總結(jié)
$_POST 可以獲 Content-Type 為 application/x-www-form-urlencoded 或者 multipart/form-data 的請求。
php://input 允許讀取 POST 的原始數(shù)據(jù)。給內(nèi)存帶來的壓力較小。不能用于 enctype="multipart/form-data"
怎么樣,學(xué)習(xí)很簡單吧?點個關(guān)注、點個喜歡、打賞都是對我的支持。