【问题标题】:Laravel 5.1: Guzzle 6 return response is not workingLaravel 5.1:Guzzle 6 返回响应不起作用
【发布时间】:2016-03-08 17:37:33
【问题描述】:

我将 Gazzle 6 与 Laravel 5.1 一起使用,并且从我正在使用的 API 返回数据时出现了奇怪的行为。这是我的代码:

$data = array(
    'id' => '112233'
);

$from = \Carbon\Carbon::now()->subDays(1)->format('d/m/Y');
$to = \Carbon\Carbon::now()->subMonths(1)->format('d/m/Y');

$first_report = $this->client->post('https://my.service.com/reporting/execute/', [
    'auth' => ['myemail@email.com', 'mypassword'],
    'form_params' => ['data' => json_encode($data)]
]);



$second_report = $this->client->get('mysecondservice.com/reports', [
    'query' => [
        'account_auth_token' => '000011122223333444455556667778889999',
        'start_date' => $to,
        'end_date' => $from
    ]
]);

return array(
    'first_report' => $first_report,
    'second_report' => $second_report
);

如果我像前一个一样将数据作为数组返回,则 first_reportsecond_report 为空。但是如果我只返回例如

return $first_report;

return $second_report;

每个报告的数据都正确返回,但我不知道那里有什么问题,因为我尝试过:json_encode 甚至 return $response()->json ... 但仍然无法正常工作。

你知道发生了什么吗?

【问题讨论】:

  • echo gettype($first_report); 带给你什么?

标签: php laravel-5.1 guzzle6


【解决方案1】:

我认为您需要在必须获得响应的对象上运行send() 函数,然后在该对象上运行getBody() 以获取响应对象,然后在该对象上运行getContents() 以获取内容作为字符串的响应。所以总的来说它看起来像

$first_report = $this->client->post('https://my.service.com/reporting/execute/', [
'auth' => ['myemail@email.com', 'mypassword'],
'form_params' => ['data' => json_encode($data)]
])->send()->getBody()->getContents();



$second_report = $this->client->get('mysecondservice.com/reports', [
'query' => [
    'account_auth_token' => '000011122223333444455556667778889999',
    'start_date' => $to,
    'end_date' => $from
]
])->send()->getBody()->getContents();

我发现 Guzzle 文档与我用来获取结果的实际方法不匹配。不确定它是否过时或我做错了,但这种方法对我有用。

【讨论】:

  • 我刚刚找到了正确的函数:->getBody()->getContents() 因为 ->send()->getBody(true);没用。
  • 很高兴你能成功!根据文档 getBody() 返回一个正文对象,而 getBody(true) 返回一个包含正文内容的字符串。
  • 好的,谢谢!您应该使用我使用的方法更新您的答案,以便其他有相同问题的用户可以看到正确的答案。
猜你喜欢
  • 2023-03-10
  • 2016-05-12
  • 2019-01-21
  • 2015-12-27
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2017-10-24
  • 2020-09-28
相关资源
最近更新 更多