php - 如何在 php guzzle 上获取响应正文?

标签 php guzzle

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

我怎样才能得到 body react ?

getBody 未返回 响应体
echo '<pre>' . print_r($response->getBody(), true) . '</pre>';

GuzzleHttp\Psr7\Stream 对象
(
[流:GuzzleHttp\Psr7\Stream:private] => 资源 ID #80
[大小:GuzzleHttp\Psr7\Stream:private] =>
[可搜索:GuzzleHttp\Psr7\Stream:private] => 1
[可读:GuzzleHttp\Psr7\Stream:private] => 1
[可写:GuzzleHttp\Psr7\Stream:private] => 1
[uri:GuzzleHttp\Psr7\Stream:private] => php://temp
[customMetadata:GuzzleHttp\Psr7\Stream:private] => 数组
(
)

)

打印体 react 如何?

最佳答案

您可以使用 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);

关于php - 如何在 php guzzle 上获取响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32119856/

相关文章:

php - 如何使用 Kubernetes API 处理流响应?

php - 如何使用 guzzleHttp 创建请求?

php - 循环 PHP 嵌套数组 - 将值提取到 Blade Views (Laravel)

javascript - 循环访问数据库中的值时获取输入框的唯一值

php - 如何将 mysql php 错误写入文本文件

php - 从文本中剥离标签?

php - Guzzle 400 错误请求

php - 检查 SQL 条目中区分大小写条目的更好方法

php - shell_exec - 记录和输出

php - 在 Laravel 5 中为 Mailgun 添加 Guzzle