【问题标题】:Guzzle returns stream empty body instead of json bodyGuzzle 返回流空体而不是 json 体
【发布时间】:2017-11-19 11:14:55
【问题描述】:

当我使用 Postman 进行 API 调用时,我收到一个 JSON 对象。这是我所期望的。

但是,当我像这样用 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

我从 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: []
  }
}

【问题讨论】:

  • 将正文转换为字符串时得到相同的响应? var_dump((string)$response->getBody());
  • $response->json(); 存在吗?不确定您使用的是哪个版本。
  • 您在使用邮递员时会发送哪些标头? (其中 8 个)。
  • 我使用的是版本 6,$response->json() 不存在

标签: php laravel guzzle


【解决方案1】:

Milan 的解决方案对我有用,但来自 API 的响应格式不正确。

我必须使用stripslashes 将其转换为 PHP 数组:

$response = $response->getBody()->__toString();
$response =  stripslashes($response);
$data = json_decode($response, true);

【讨论】:

    【解决方案2】:

    如果$response->getBody()->getContents() 不适合您,请尝试:

    $response->getBody()->__toString();
    

    如here 所述,有时getContents 的流指针已经在流的末尾,然后它返回空响应,但__toString 默认重置它。

    【讨论】:

    • 这个对我有用。有什么办法可以将此字符串转换为 PHP 数组?
    • 你让我很开心。这让我真的很生气,直到我找到你的答案。这似乎仍然没有解决,我根本不明白他们为什么用流指针这样做。有什么理由和方法可以重置吗?
    【解决方案3】:

    getBody() 返回一个流。如果您想一次获取所有内容,可以使用getContents() 方法并在使用时解码 json(如果需要)

    $payload = json_decode($response->getBody()->getContents());
    

    进一步阅读 - Guzzle Responses

    【讨论】:

    • 我找到的最佳答案是找不到对象或使用 guzzle 为空,谢谢
    • 答案可以简化为json_decode($response->getBody())。 json_decode() 会将 body 转换为 string,这与调用 getContents() 的效果相同。
    • @MaksimIvanov 不,它不会将正文投射到string。
    • @MaksimIvanov json_decode 期望第一个参数是字符串。 getBody() 不返回字符串。
    猜你喜欢
    • 2016-11-08
    • 2020-12-10
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2023-03-15
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多