donglanzhan7151 2019-03-12 11:25
浏览 1636
已采纳

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

I'm calling an API via Guzzle.

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);
}

My json test (outputted from "1") is

{
  "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"
}

But, in code "2" I have an empty string and in code "3" (output from "checkError" method) I have null.

If I comment out the checkError method, I would expect another time same json in fragment 2, but I have an empty string. Why this behaviour?

  • 写回答

1条回答 默认 最新

  • dpwdldgn43486 2019-03-13 05:09
    关注

    It's expected behaviour, because response body is a stream (read more in PSR-7 spec).

    To be able to read the body again, you need to call ->getBody()->rewind() to rewind the stream to the beginning. Just be aware that it can cause an exception in rare cases, because not all stream types support rewind operation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况