【问题标题】:Curl Response handling with Guzzle 6.2 with Laravel 5.3使用 Guzzle 6.2 和 Laravel 5.3 处理卷曲响应
【发布时间】:2023-03-10 22:17:01
【问题描述】:

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

我正在使用以下代码发出 get 请求:

$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: []
  }
}

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

我在这里做错了什么?

【问题讨论】:

  • 你为什么不使用基本的 php curl 而不是这个

标签: php laravel-5.3 guzzle


【解决方案1】:

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

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

可能有必要(在某些情况下)将结果转换为字符串,因为实际结果是一个流。

Guzzle documentation: Responses

【讨论】:

  • 嗨,杰弗里,我尝试了 getBody() 方法,该方法输出以下响应: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: [] }
  • 将其转换为字符串,您将拥有实际的正文:$output = (string) $response-&gt;getBody();
  • 不客气!我已经更新了我的帖子以包含演员表。
猜你喜欢
  • 2015-07-31
  • 2016-05-12
  • 2018-04-27
  • 1970-01-01
  • 2017-10-24
  • 2019-12-27
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多