如何在 php guzzle 上获得响应 body?

How get response body on php guzzle?

use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('http://httpbin.org/post', array());

如何获得 body 响应?

getBody未返回响应body

echo '<pre>' . print_r($response->getBody(), true) . '</pre>';
GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #80
    [size:GuzzleHttp\Psr7\Stream:private] => 
    [seekable:GuzzleHttp\Psr7\Stream:private] => 1
    [readable:GuzzleHttp\Psr7\Stream:private] => 1
    [writable:GuzzleHttp\Psr7\Stream:private] => 1
    [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
    [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
        (
        )

)

如何打印 body 响应?

您可以使用getContents 方法来拉取响应的正文。

$response = $this->client->get("url_path", [
                'headers' => ['Authorization' => 'Bearer ' . $my_token]
            ]);
$response_body = $response->getBody()->getContents();
print_r($response_body);

当您拉取 make guzzle 请求时,您通常会将其放入 try catch 块中。此外,您还需要将该响应解码为 JSON 以便您可以像使用对象一样使用它。这是一个如何做的例子。在这种情况下,我正在使用服务器进行身份验证:

    try {

        $response = $this->client->post($my_authentication_path, [
            'headers' => ['Authorization' => 'Basic ' . $this->base_64_key,
                            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
                            ],
            'form_params'    => ['grant_type' => 'password',
                            'username' => 'my_user_name',
                            'password' => 'my_password']
        ]);

        $response_body = $response->getBody()->getContents();

    } catch (GuzzleHttp\Exception\RequestException $e){
        $response_object = $e->getResponse();
        //log or print the error here.
        return false;
    } //end catch

    $authentication_response = json_decode($response_body);
    print_r($authentication_response);