laravel Guzzle 返回流空体而不是 json 体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44593272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Guzzle returns stream empty body instead of json body
提问by Emeka Mbah
When I use Postman to make an API call I receive a JSON object..which is what I expected.
当我使用 Postman 进行 API 调用时,我收到了一个 JSON 对象……这正是我所期望的。
However When I make same call with Guzzle like so:
但是,当我像这样与 Guzzle 打相同的电话时:
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.dev/']);
$response = $client->request('GET', 'search', [
'verify' => false,
]);
var_dump($response->getBody()); //null
var_dump($response); //returns below
I get dump below from Guzzle
我从 Guzzle 那里得到了转储
Response {#304 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:8 [▼
"Server" => array:1 [?]
"Content-Type" => array:1 [▼
0 => "application/json"
]
"Transfer-Encoding" => array:1 [?]
"Connection" => array:1 [?]
"Cache-Control" => array:1 [?]
"Date" => array:1 [?]
"X-RateLimit-Limit" => array:1 [?]
"X-RateLimit-Remaining" => array:1 [?]
]
-headerNames: array:8 [▼
"server" => "Server"
"content-type" => "Content-Type"
"transfer-encoding" => "Transfer-Encoding"
"connection" => "Connection"
"cache-control" => "Cache-Control"
"date" => "Date"
"x-ratelimit-limit" => "X-RateLimit-Limit"
"x-ratelimit-remaining" => "X-RateLimit-Remaining"
]
-protocol: "1.1"
-stream: Stream {#302 ▼
-stream: stream resource @15 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
回答by peterm
getBody()
returns a stream. If you want to get all the content at once you can use getContents()
method and decode json while at it (if you need to)
getBody()
返回一个流。如果您想一次获取所有内容,您可以使用getContents()
方法并在其中解码 json(如果需要)
$payload = json_decode($response->getBody()->getContents());
Further reading - Guzzle Responses
进一步阅读 - Guzzle Responses
回答by Milan Markovic
If $response->getBody()->getContents() doesn't work for you, try:
如果 $response->getBody()->getContents() 对您不起作用,请尝试:
$response->getBody()->__toString();
As mentioned here, sometimes getContents's stream pointer is already at the end of stream and then it returns empty response, but __toString resets it by default.
正如这里提到的,有时 getContents 的流指针已经在流的末尾,然后它返回空响应,但 __toString 默认重置它。