简体   繁体   English

Laravel Guzzle不起作用,但Curl确实如此

[英]Laravel Guzzle doesn't work but Curl does

I'm using Guzzle for working with external API. 我正在使用Guzzle来处理外部API。

I'm using it this way: 我这样使用它:

$client = new Client;
$request = $client->request('GET', 'https://api.callrail.com/v1/companies.json', [
    'headers' => [
        'Authorization' => 'Token token="my_api_string"'
    ]
]);

return dd($request);

this is the output 这是输出

Stream {#255 ▼
  -stream: stream resource @280 ▶}
  -size: null
  -seekable: true
  -readable: true
  -writable: true
  -uri: "php://temp"
  -customMetadata: []
}

but when I use just curl like this 但是当我像这样使用卷曲时

$api_key = 'my_api_string';

$ch = curl_init($api_url);

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Token token=\"{$api_key}\""));

$json_data = curl_exec($ch);

return dd($json_data);

the output looks as expected 输出看起来像预期的那样

{"page":1,"per_page":100,"total_pages":1,"total_records":11,
....
....

what am I doing wrong with the Guzzle? 我对Guzzle做错了什么?

You have set up the Guzzle request correctly, you just need to do more with the $request after you retrieve it. 您已正确设置Guzzle请求,您只需要在检索后使用$request执行更多操作。

Add this line in after your request: 在您的请求后添加此行:

$result = json_decode($request->getBody());

Adding it in to your code it would look like this: 将其添加到您的代码中它将如下所示:

$client = new Client;
$request = $client->request('GET', 'https://api.callrail.com/v1/companies.json', [
    'headers' => [
        'Authorization' => 'Token token="my_api_string"'
    ]
]);

$result = json_decode($request->getBody());

return dd($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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