简介:Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.
安装: composer require guzzlehttp/guzzle
案例:
<?php
namespace App\Http\Controllers;
use GuzzleHttp\RequestOptions;
class TestController extends Controller
{
protected $headers = [];
public function __construct()
{
$this->headers = [
'time' => time(),
];
}
public function index()
{
$uri = 'http://scrm.xcyc.com/api/test';
$params['a'] = 1;
$params['b'] = 2;
$options = [
RequestOptions::TIMEOUT => 3,
RequestOptions::HTTP_ERRORS => false,
RequestOptions::HEADERS => $this->headers,
RequestOptions::QUERY => $params,
];
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', $uri, $options);
$contents = $res->getBody()->getContents();
// 失败的情况
if ($res->getStatusCode() != 200) {
throw new \Exception(__('心诚直销网服务请求失败'), $res->getStatusCode());
}
return json_decode($contents, true);
}
}