Guzzle3发送原始POST请求

5
我正在处理一个使用Guzzle3(v3.9.3)的项目,我想知道如何发送原始的POST请求。我已经尝试了这些解决方案,但是它们都对我没有用。我正在使用这个Guzzle3 手册
解决方案:
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' =>  'Bearer '.$token,
'Accept' => 'application/json'
));

$body = '{"filter_":{"user":{"email":"aaa@test.com"}}}';
$req = $client->post($url, array(), $body,
array(
 'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true)); 

解决方案2:

$client = new Client();
$client->setDefaultOption('headers', array(
 'Authorization' =>  'Bearer '.$token,
'Accept' => 'application/json'
));

$body = '{"filter_":{"user":{"email":"aaa@test.com"}}}';

$req = $client->post($url, array(), array(),
 array(
    'cert' => array($certification, 'password'),
 )
);

$req->setBody($body);
$response = json_decode($client->send($req)->getBody(true)); 

这些解决方案都对我不起作用,

错误: 客户端错误响应 [状态码] 404 [原因短语] 未找到 [URL]

我在网上尝试了一些解决方案 (但是针对Guzzle6),它可以工作,但我没有得到正确的结果(它没有考虑我发送的过滤器,即邮件地址,所以我得到了所有结果)。

...
$body = array(
'filter_' => array(
   'user' => array( "email" => $email )
 )
);

$req = $client->post($url, array(),array('body'=> $body),
array(
    'cert' => array($certification, 'password'),
)
);
...

在Postman上,对Web服务的调用可以正常工作。

提前感谢。


你为什么只限于使用Guzzle3?你能否提供有关如何配置Postman请求的更多信息?(如果可以在Postman中完成,那么也可以在Guzzle中完成。) - colonelclick
1个回答

2
我将在此发布回复以便有需要的人参考,我必须将所有代码块放置在try catch语句中。
try{
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' =>  'Bearer '.$token,
));
$body = '{"filter_":{"user":{"email":"aaa@test.com"}}}';
$req = $client->post($url, array(), $body,
array(
 'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true)); 
catch(Guzzle\Http\Exception\BadResponseException $e){
        $response = json_decode($e->getResponse()->getBody(),true);
}

你说,捕获异常并将其解码为正确的数据是一种解决方案? - yergo
当Web服务返回空响应时,我会收到我提到的错误。当我添加了带有BadResponseException的catch块,并且调试$e后,我发现我收到了空响应!! - Hanane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接