Object of class GuzzleHttp\Psr7\Request could not be converted to string
Asked Answered
B

3

8

I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.

use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();

$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);

if ($res->getStatusCode() == 200)
{
 $json = (string)$res->getBody();
 return $json;
}

and I've got this error on log: Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string

what is wrong with my code? please kindly help me. fyi, this error not always happen. sometimes it show this error, sometimes success.

thank you

Benefactor answered 7/6, 2017 at 4:30 Comment(2)
try this url github.com/MatissJanis/oc-mail/commit/…Irmgardirmina
For me, the problem was that I'd previously accidentally saved to cache a "response" (result of $client->request()) instead of using ->getBody()->getContents(), and so then I kept getting confused when I saw these errors because I thought they were talking about a different Guzzle request, but it was just that I was reading a variable from cache expecting it to be a string, and it was really a response object.Axletree
L
14
$json = $res->getBody()->getContents();

try this

Lynwoodlynx answered 7/6, 2017 at 4:44 Comment(0)
P
0

Try this.....

    try {
        $parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
        $res = $client->request('GET', $url, $parameter);

        if ($res->getStatusCode() == 200)
          {
             return $res->getBody()->getContents();
          }
    }catch(Exception $e){
        echo 'Caught exception: ',  $e->getMessage();
    }
Privateer answered 7/6, 2017 at 5:26 Comment(0)
V
0
$response = $client->post('http:yanjye.com3', ['phone' => '00','password' => '5555',]);
        if ($response->getStatusCode() == 200){
            $json = (string)$response->getBody();
            return $json;
            }
         var_dump( $response);
         die();


Hello, brother, I think this is the Good way to  which is Working On both  laravel 5.2[larave 5.2]



i have removed Httm 
[laraver 5.2][1]

and use this code :

  [1]: https://laravel.com/docs/7.x/http-client`
Vomiturition answered 12/4, 2020 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.