如何获得关于php guzzle的响应主体?

时间:2015-08-20 13:38:51

标签: php guzzle

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

我如何得到身体反应?

getBody 未返回响应正文

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
        (
        )

)

如何打印身体反应?

1 个答案:

答案 0 :(得分:3)

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

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

当你提出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);