简体   繁体   中英

Laravel 5.1: Guzzle 6 return response is not working

I'm using Gazzle 6 with Laravel 5.1 and I'm having a strange behaviour returning my data from the APIs I'm using. This is my code:

$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
);

If I return the data as an array like the previous one the first_report and second_report are empty. But if I return only for example

return $first_report;

or

return $second_report;

The data is returned correctly for each report but I don't know what is the issue there, because I have tried with: json_encode or even return $response()->json... but still not working.

Do you have any idea about what's going on?

I think you need to run the send() function on the object you have to get the response, then run getBody() on that to get the response object, then run getContents() on that to get the contents of the response as a string. So in total it would look like

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

I find the Guzzle documentation does not match up with the actual methods I use to get the results. Not sure if it's out of date or if I'm doing it wrong, but this method works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM