Guzzle是一个PHP的HTTP客户端,用来垂手可得地发送请求,并集成到咱们的WEB服务上。php
安装
看到文档的安装方式会不知道怎么弄,由于composer安装列表没有下载方式json
(1)打开项目的composer.json文件,添加GuzzleHttp这个安装包app
(2)执行composer updatecomposer
(3)而后项目就有了this
使用GuzzleHttp
(1)引入url
(2)请求代码spa
(3)发起请求,这就是简单的使用code
源码
base.php文件token
<?php namespace app\huanxin\controller; use think\config; use think\Controller; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class Base extends Controller { protected $orgname; protected $appname; protected $client_ID; protected $client_Secret; protected $request_url; public function __construct() { $this->orgname = config::get('orgname'); $this->appname = config::get('appname'); $this->client_ID = config::get('client_ID'); $this->client_Secret = config::get('client_Secret'); $this->request_url = 'https://a1.easemob.com/'; } /** * author:咔咔 * * 基础请求地址 * @return string */ public function baseUrl() { return $this->request_url . $this->orgname . '/' . $this->appname . '/'; } /** * 发送请求 * @param $method 请求方式 * @param array $params 请求参数 * @param $options * @return array|mixed * @throws Error */ public function request($method, $url, $params = [], $options = []) { $config = ['base_uri' => $this->baseUrl()]; $client = new Client($config); $header = [ 'Content-Type' => 'application/json', 'Accept' => 'application/json', ]; $data = ['connect_timeout' => 30, 'headers' => $header]; if ($method == 'GET') { $data['query'] = $params; } else { $data['json'] = $params; } $options && $data = array_merge($data, $options); $body = []; try { $res = $client->request($method, $url, $data); $body = \GuzzleHttp\json_decode($res->getBody()->getContents(), 1); } catch (RequestException $e) { throw new Error($e->getMessage(), -1); } return $body; } /** * author:咔咔 * * 获取token * @throws Error */ public function getTokenFromServer() { $data = [ 'grant_type' => 'client_credentials', 'client_id' => $this->client_ID , 'client_secret' => $this->client_Secret ]; $result = $this->request('POST', 'token', $data); return $result; } }
error.php文件文档
<?php namespace app\huanxin\controller; use Exception; class Error extends \Exception { public function __construct($message = "", $code = 0, Exception $previous = null) { parent::__construct($this->_getMessage($message), $code, $previous); } // TODO 异常信息过滤 private function _getMessage($msg) { $message = $msg; return $message; } }
index.php文件
<?php namespace app\huanxin\controller; use think\config; class Index extends Base { public function index() { $data = $this->getTokenFromServer(); dump($data);die; } }