2016-10-03 127 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