使用带有Laravel 5.3的Guzzle 6.2处理卷曲响应

时间:2017-02-04 16:09:04

标签: php laravel-5.3 guzzle

我正在尝试使用Guzzle 6.2和Laravel 5.3从端点获取JSON响应。

我使用以下代码发出获取请求:

$client = new GuzzleHttp\Client([
  'base_uri' => 'https://192.xx.xxx.xx6/',
  'timeout'  => 2.0
]);

$response = $client->request('GET',
  '/fineract-provider/api/v1/clients/388?tenantIdentifier=default&pretty=true', [
    'verify' => false,
    'auth' => ['<username>', '<password>']
  ]
);

var_dump($response);

其中输出以下响应:

Response {#282
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:7 [
    "Server" => array:1 [
      0 => "Apache-Coyote/1.1"
    ]
    "Access-Control-Allow-Origin" => array:1 [
      0 => "*"
    ]
    "Access-Control-Allow-Methods" => array:1 [
      0 => "GET, POST, PUT, DELETE, OPTIONS"
    ]
    "Content-Type" => array:1 [
      0 => "application/json"
    ]
    "Transfer-Encoding" => array:1 [
      0 => "chunked"
    ]
    "Vary" => array:1 [
      0 => "Accept-Encoding"
    ]
    "Date" => array:1 [
      0 => "Sat, 04 Feb 2017 15:51:10 GMT"
    ]
  ]
  -headerNames: array:7 [
    "server" => "Server"
    "access-control-allow-origin" => "Access-Control-Allow-Origin"
    "access-control-allow-methods" => "Access-Control-Allow-Methods"
    "content-type" => "Content-Type"
    "transfer-encoding" => "Transfer-Encoding"
    "vary" => "Vary"
    "date" => "Date"
  ]
  -protocol: "1.1"
  -stream: Stream {#280
    -stream: stream resource @297
      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: []
  }
}

但这不是我期望的回应。但是,当我在浏览器中发出相同的请求时,它会提供正确的输出,如下所示:

enter image description here

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

Response对象包含的信息不仅仅是响应。你可以得到这样的实际输出:

$output = (string)$response->getBody();

可能需要(在某些情况下)将结果强制转换为字符串,因为实际结果是流。

Guzzle documentation: Responses