在Symfony2中访问HTTP PUT数据 [英] access HTTP PUT data in Symfony2
问题描述
通过HTTP PUT,我将以下json发送到我的Web服务,并由return new Response($request->getContent());
验证:
{"company_id":13}
在我的Web服务中,我试图从请求中按其标签检索数据:
var_dump("COMPANY ID ".$request->request->getInt('company_id')); //returns 0
我也尝试过:
//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
symfony2书仅提到如何从GET和POST中获取数据,如何从PUT请求中获取数据?
您是从$request->getContent()
获取它的,只是json_decode
它,您应该获取一个对象,以便可以对其进行访问.示例:
$data = json_decode($request->getContent());
var_dump("COMPANY ID " . $data->company_id);
编辑以添加更多说明.
Symfony Http Foundations get
方法基本上只是$request->attributes->get
,$request->query->get
和$request->request->get
的别名",因此,如果一个返回0或false,或者其他任何值,很可能另一个也将返回. /p>
由于HTTP PUT将数据作为正文发送,所以Request对象不会尝试以任何方式对其进行解码,因为它可能具有多种不同的格式(JSON,XML,非标准格式...).如果希望通过get
方法调用来访问它,则必须手动对其进行解码,然后将其添加到其request
或query
属性中.
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?
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.
这篇关于在Symfony2中访问HTTP PUT数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!