打不开公式编辑器(公式编辑器用不了)
963
2022-05-30
Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。
安装
看到文档的安装方式会不知道怎么弄,因为composer安装列表没有下载方式
(1)打开项目的composer.json文件,添加GuzzleHttp这个安装包
(2)执行composer update
(3)然后项目就有了
使用GuzzleHttp
(1)引入
(2)请求代码
(3)发起请求,这就是简单的使用
源码
base.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文件
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文件
namespace app\huanxin\controller;
use think\config;
class Index extends Base
{
public function index()
{
$data = $this->getTokenFromServer();
dump($data);die;
}
}
项目目录
PHP
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。