access HTTP PUT data in Symfony2

荒凉一梦 提交于 2019-12-12 15:24:34

问题


Via HTTP PUT I send the following json to my webservice, verified by return new Response($request->getContent());:

{"company_id":13}

In my webservice I am trying to retrieve the data by its tag from the request:

var_dump("COMPANY ID ".$request->request->getInt('company_id')); //returns 0

I've also tried:

//the 2 below should only work on GET from what I read
var_dump("COMPANY ID ".$request->get('company_id')); //returns nothing
var_dump("COMPANY ID ".$request->query->getInt('company_id')); //returns 0

The symfony2 book only mentions how to get data from GET and POST, how do I retrieve data from a PUT request?


回答1:


You are getting it from $request->getContent(), just json_decode it and you should get an object, so you can access it then. Example:

$data = json_decode($request->getContent());
var_dump("COMPANY ID " . $data->company_id);

Edit to add a little bit more explanation.

Symfony Http Foundations get method is basically just an "alias" for $request->attributes->get, $request->query->get, and $request->request->get, so if one returns 0 or false, or whatever, quite probably the other will too.

Since HTTP PUT sends data as body, the Request object does not try to decode it in any way, because it could have been in multiple different formats(JSON, XML, non-standard,...). If you wish to access it through get method call, you will have to decode it manually and then add it to its request or query properties.




回答2:


You will never get it as a single parameter, because it is not a parameter. It's a raw content that you have to decode yourself.

HTTP protocol does not know anything about JSON / XML / serializing / whatever.

It only sees a text string.

As @slaxOr said, you'll have to get from the request and decode it yourself (there may be bundles that do it for you, but I am not aware of them).



来源:https://stackoverflow.com/questions/36858279/access-http-put-data-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!