如何返回Guzzle JSON响应 [英] How to return Guzzle JSON response
问题描述
我正在使用Guzzle发出一个返回JSON的aSync请求.通话正常,响应正常,但是:
I am using Guzzle to make a aSync request that returns JSON. The call is working fine and the response is ok, however:
$client = new Client();
$promise = $client->requestAsync($requestType ,$this->url.$resource, // endpoint
[
'auth' => [ // credentials
$this->username,
$this->password
],
'json' => $payload, // the package
'curl' => [ // some curl options
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_RETURNTRANSFER => true,
],
'headers' => [ // custom headers
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
]
);
$response = $promise->wait();
echo $response->getStatusCode().'<br /><br />';
// Error handling
if($response->getStatusCode() != 200){
// Error Handling
}else{
echo $response->getBody(true);
}
如果我回显response-> getBody(),我会看到JSON字符串,但是如果将其分配给属性print_r或返回它,则会得到:
if I echo response->getBody() I see the JSON string, but if I assign it to a property, print_r, or return it I get:
GuzzleHttp\Psr7\Stream Object ( [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #245 [size:GuzzleHttp\Psr7\Stream:private] => [seekable:GuzzleHttp\Psr7\Stream:private] => 1 [readable:GuzzleHttp\Psr7\Stream:private] => 1 [writable:GuzzleHttp\Psr7\Stream:private] => 1 [uri:GuzzleHttp\Psr7\Stream:private] => php://temp [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array ( ) )
我需要使用JSON来验证我对服务的响应.我怎样才能做到这一点?我已经阅读了文档,但是显然我遗漏了一些东西.
I need to use the JSON to validate my response from the service. How can I do this? I have gone through the docs, but am I obviously missing something.
基本上是在将json getBody输出分配为$ json的过程中:
Essentially along the lines of assigning the json getBody output to say $json:
if($json->first_field > 0)
任何帮助表示赞赏. 问候
Any Help appreciated. Regards
推荐答案
在对SO进行了更多研究之后,我首先跌入了这篇文章
After some more research on SO I tumbled head first into this post
基本上,执行以下操作将返回原始输出.
Essentially doing the following will return the raw output.
return $response->getBody()->getContents();
巨大的头痛消失了.希望这对某人有帮助
Huge headache gone. Hope this helps someone
这篇关于如何返回Guzzle JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!