Laravel使用Guzzle调用外部的http接口
Guzzle是一个PHP的http client,用来发送http请求。在Laravel里使用,只需要引入guzzle包。
通过composer引入guzzle:
composer require guzzlehttp/guzzle:~6.0
或者在 composer.json里添加依赖:
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
使用示例:
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
echo $res->getStatusCode();
// 200
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
}