gpt4 book ai didi

php - Guzzle getContents()->getBody() - 第二次调用返回空字符串

转载 作者:行者123 更新时间:2023-12-04 09:26:33 26 4
gpt4 key购买 nike

我正在通过 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()将流倒回到开头。请注意,在极少数情况下它可能会导致异常,因为并非所有流类型都支持倒带操作。

关于php - Guzzle getContents()->getBody() - 第二次调用返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55120359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com