2016-10-03 128 views
0

因此,這是一個應該接受POST請求下列參數的API:如何將JSON請求和表單數據請求一起發送?

token (as form data) 
apiKey (as form data) 
{ 
"notification": { 
    "id": 1, 
    "heading": "some heading", 
    "subheading": "some subheading", 
    "image": "some image" 
    } 
} (JSON Post data) 

現在我的問題是,我不能夠在同一個POST請求的表單數據和JSON數據一起發送。因爲,表單數據使用Content-Type: application/x-www-form-urlencoded和JSON需要有Content-Type: application/json我不知道如何將它們都發送到一起。我正在使用郵差。

編輯:

因此API會調用該函數create,我需要做這樣的事情:

public function create() { 


    $token = $this -> input -> post('token'); 
    $apiKey = $this -> input -> post('apiKey'); 
    $notificationData = $this -> input -> post('notification'); 

    $inputJson = json_decode($notificationData, true); 
    } 

但不是我不能夠得到JSON數據和表格數據一起。

我不得不這樣做是爲了獲得JSON數據

public function create(){ 
$notificationData = file_get_contents('php://input'); 
$inputJson = json_decode($input, true); 
} // can't input `token` and `apiKey` because `Content-Type: application/json` 
+0

請發表您的代碼。 –

+0

您是否嘗試過直接發送JSON而不將內容類型設置爲'application/json'? –

+0

它看起來像一個表單帖子,其中3個鍵具有3個字符串值。 – jeroen

回答

3

幾種可能性:

  1. 發送令牌和鍵查詢參數和JSON作爲請求體:

    POST /my/api?token=val1&apiKey=val2 HTTP/1.1 
    Content-Type: application/json 
    
    {"notification": ...} 
    

    在PHP中,您通過獲得密鑰和令牌和身體通過json_decode(file_get_contents('php://input'))

  2. 送在Authorization HTTP頭中的令牌和鍵(或任何其他自定義頁眉):

    POST /my/api HTTP/1.1 
    Authorization: MyApp TokenVal:KeyVal 
    Content-Type: application/json 
    
    {"notification": ...} 
    

    你得到通過頭,例如,$_SERVER['HTTP_AUTHORIZATION']和自己解析它。

  3. 使請求主體(不是很首選)的標誌和關鍵部分:

    POST /my/api HTTP/1.1 
    Content-Type: application/json 
    
    {"key": val1, "token": val2, "notification": ...} 
    
+0

嗨,規範是'token'和'apiKey'是POST數據。那麼不應該使用解決方案#1,對吧? –

+0

要清楚:解決方案1將數據放入** URL查詢字符串**中。即使您通過PHP中的$ _GET訪問它,也不會***「獲取數據」。這是PHP的一部分錯誤命名。使用POST方法的HTTP請求是POST請求。 ** URL查詢字符串**中的數據不是***「GET數據」。 – deceze

+0

所以,不,沒有理由不使用解決方案1. – deceze