如何使用Slim框架获取POST请求实体


How to get the POST request entity using Slim framework

我已经使用android java发送了JSON数据,方法是在如下的post实体中设置它:

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

如何在使用Slim frameworkphp中接收此json数据?我试过这个:

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

JSON未解析为$_POST超全局。在$_POST中,您可以找到表单数据。您可以在请求正文中找到JSON。像下面这样的东西应该有效。

$app->post("/recipe/insert/", "authenticate", function() use ($app) { 
    $json = $app->request->getBody(); 
    var_dump(json_decode($json, true));
});

您需要获取响应主体。将其保存在变量中。之后,验证变量是否为null,然后解码JSON。

$app->post("/recipe/insert/", "authenticate", function() use ($app) { 
$entity = $app->request->getBody(); 
if(!$entity)
   $app->stop();
$entity = json_decode($entity, true);
});