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 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败