Guzzle 返回流空正文而不是 json 正文

2022-08-30 18:38:51

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

然而,当我像这样与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: []
  }
}

答案 1

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

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

延伸阅读 - 咕噜咕噜的回应


答案 2

如果对您不起作用,请尝试:$response->getBody()->getContents()

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

如前所述,有时 的流指针已经在流的末尾,然后它返回空响应,但默认情况下会重置它。getContents__toString


推荐