Guzzle getContents()->getBody() - 第二次调用 return 空字符串
Guzzle getContents()->getBody() - Second calls return empty string
我正在通过 Guzzle 呼叫 API。
public function request(string $method, string $uri, array $data = [], array $headers = [])
{
$response = $this->getClient()->$method($uri, [
'headers' => $headers,
'query' => $data,
]);
echo "1";
var_dump($response->getBody()->getContents());
$this->checkError($response);
echo "2";
var_dump($response->getBody()->getContents());
return $response;
}
public function checkError($response)
{
$json = json_decode($response->getBody()->getContents());
echo "3";
var_dump($json);
}
我的 json 测试(从“1”输出)是
{
"args":{
},
"headers":{
"Authorization":"Basic dXNlcm5hbWU6cGFzc3dvcmQ=",
"Host":"httpbin.org",
"User-Agent":"GuzzleHttp/6.3.3 curl/7.59.0 PHP/7.2.4"
},
"origin":"1.2.3.4, 1.2.3.4",
"url":"https://httpbin.org/get"
}
但是,在代码“2”中我有一个空字符串,在代码“3”中("checkError" 方法的输出)我有空字符串。
如果我注释掉 checkError 方法,我希望片段 2 中的另一个时间相同 json,但我有一个空字符串。为什么会出现这种行为?
这是预期的行为,因为响应主体是一个流(在 PSR-7 spec 中阅读更多信息)。
为了能够再次阅读正文,您需要调用 ->getBody()->rewind()
将流倒回到开头。请注意,在极少数情况下它可能会导致异常,因为并非所有流类型都支持倒带操作。
我正在通过 Guzzle 呼叫 API。
public function request(string $method, string $uri, array $data = [], array $headers = [])
{
$response = $this->getClient()->$method($uri, [
'headers' => $headers,
'query' => $data,
]);
echo "1";
var_dump($response->getBody()->getContents());
$this->checkError($response);
echo "2";
var_dump($response->getBody()->getContents());
return $response;
}
public function checkError($response)
{
$json = json_decode($response->getBody()->getContents());
echo "3";
var_dump($json);
}
我的 json 测试(从“1”输出)是
{
"args":{
},
"headers":{
"Authorization":"Basic dXNlcm5hbWU6cGFzc3dvcmQ=",
"Host":"httpbin.org",
"User-Agent":"GuzzleHttp/6.3.3 curl/7.59.0 PHP/7.2.4"
},
"origin":"1.2.3.4, 1.2.3.4",
"url":"https://httpbin.org/get"
}
但是,在代码“2”中我有一个空字符串,在代码“3”中("checkError" 方法的输出)我有空字符串。
如果我注释掉 checkError 方法,我希望片段 2 中的另一个时间相同 json,但我有一个空字符串。为什么会出现这种行为?
这是预期的行为,因为响应主体是一个流(在 PSR-7 spec 中阅读更多信息)。
为了能够再次阅读正文,您需要调用 ->getBody()->rewind()
将流倒回到开头。请注意,在极少数情况下它可能会导致异常,因为并非所有流类型都支持倒带操作。