我正在使用Guzzle向我正在开发的网络服务发出HTTP POST请求。
我为此操作使用服务描述JSON文件,如下所示:
{
"name": "My webservice",
"apiVersion": "1.0",
"description": "My webservice is a webservice",
"operations": {
"createStuff": {
"httpMethod": "POST",
"uri": "/stuff/{accountid}/{product}/things",
"summary": "Creates a thing",
"parameters": {
"accountid": {
"location": "uri",
"description": "The account ID of the stuff"
},
"product": {
"location": "uri",
"description": "The product of the stuff"
}
},
"additionalParameters": {
"location": "body"
}
}
}
}
完成这项工作的代码分为两类(我保证不会很长):
StuffApi
class StuffApi
{
protected $client;
public function __construct(ClientInterface $client, $baseUrl)
{
$this->client = $client;
//tell the client what the base URL to use for the request
$this->client->setBaseUrl($baseUrl);
//fill the client with all the routes
$description = ServiceDescription::factory(__DIR__."/../resources/routes.json");
$this->client->setDescription($description);
}
public function create(StuffEntity $entity)
{
$postArray = array('postParam1' => $entity->getPostParam1(), 'postParam2' => $entity->getPostParam2());
$params = array(
'parameters' => json_encode($postArray),
'accountid' => $entity->getAccountId(),
'product' => $entity->getProduct()
);
$response = $this->performCall('createStuff', $params);
$locationAsArray = $response->getHeader('location')->raw();
$location = $locationAsArray[0];
return $location;
}
private function performCall($operationName, $parameters)
{
$command = $this->client->getCommand($operationName, $parameters);
$command->prepare();
$response = $this->client->execute($command);
return $response;
}
}
MySubscriber
class MySubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array('request.success' => 'onRequestSuccess');
}
public function onRequestSuccess(Event $event)
{
var_dump($event['request']->getPostFields());
}
}
使用上述类的代码是:
$client = new Guzzle\Service\Client();
$subscriber = new MySubscriber;
$client->addSubscriber($subscriber);
$api = new StuffApi($client, 'http://url.to.webservice.com/');
$x = new StuffEntity();
$x->setAccountId(654143);
$x->setProduct('theproduct');
$x->setPostParam1(1);
$x->setPostParam2('989054MNBNMO5490BMN54');
$result = $api->createStuff($x);
好的,现在问题是,因为我在var_dump
方法中执行了POST
个onRequestSuccess
字段,所以我希望看到值1
和{{ 1}}我在上面设置。
相反,我明白了:
"989054MNBNMO5490BMN54"
我真的需要使用object (Guzzle\Http\QueryString) [35]
protected 'fieldSeparator' => string '&' (length=1)
protected 'valueSeparator' => string '=' (length=1)
protected 'urlEncode' => string 'RFC 3986' (length=8)
protected 'aggregator' => null
protected 'data' =>
array (size=0)
empty
方法访问请求中使用的POST信息。它为什么不存在?或者我试图以错误的方式得到它?
提前谢谢。
PS:我使用的Guzzle版本是 3.8.1 。