How to get the POST request entity using Slim fram

2019-05-27 07:20发布

I have sent JSON data using android java by setting it in the post entity like this:

HttpPost httpPostRequest = new HttpPost(URLs.AddRecipe);
StringEntity se = new StringEntity(jsonObject.toString());
httpPostRequest.setEntity(se);

How can I receive this json data in the php , where I am using Slim framework ? I have tried this:

$app->post('/recipe/insert/', 'authenticate', function() use ($app) { 
            $response = array();
            $json = $app->request()->post(); 
});

2条回答
走好不送
2楼-- · 2019-05-27 07:25

You need to get the response body. Save it in a variable. After that, verify if the variable is null and then decode your JSON.

$app->post("/recipe/insert/", "authenticate", function() use ($app) { 
$entity = $app->request->getBody(); 

if(!$entity)
   $app->stop();

$entity = json_decode($entity, true);

});
查看更多
欢心
3楼-- · 2019-05-27 07:37

JSON is not parsed into $_POST superglobal. In $_POST you can find form data. JSON you can find in request body instead. Something like following should work.

$app->post("/recipe/insert/", "authenticate", function() use ($app) { 
    $json = $app->request->getBody(); 
    var_dump(json_decode($json, true));
});
查看更多
登录 后发表回答