Files
cycle_api/app/Service/HttpService.php
2024-03-27 00:11:26 +08:00

87 lines
3.1 KiB
PHP

<?php
namespace App\Service;
use App\Bean\Service\HttpServiceConfigBean;
use App\Bean\Service\HttpServiceReturnLogBean;
use App\Tools\Logs;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class HttpService
{
protected Client $client;
const REQ_METHOD_GET = 'GET';
const REQ_METHOD_POST = 'POST';
public function __construct()
{
$this->client = new Client();
}
public function getClient(): Client
{
return $this->client;
}
public function get(string $endpoint, array $data = [], HttpServiceConfigBean $configBean = null)
{
if ($configBean === null) $configBean = new HttpServiceConfigBean();
$oHttpServiceReturnLogBean = $this->request(self::REQ_METHOD_GET, $endpoint, $data, $configBean);
if ($configBean->isIsReturnJson() === true) {
return json_decode($oHttpServiceReturnLogBean->getResponseBody(), false);
}
return $oHttpServiceReturnLogBean->getResponseBody();
}
public function post(string $endpoint, array $data = [], HttpServiceConfigBean $configBean = null)
{
if ($configBean === null) $configBean = new HttpServiceConfigBean();
$oHttpServiceReturnLogBean = $this->request(self::REQ_METHOD_POST, $endpoint, $data, $configBean);
if ($configBean->isIsReturnJson() === true) {
return json_decode($oHttpServiceReturnLogBean->getResponseBody(), false);
}
return $oHttpServiceReturnLogBean->getResponseBody();
}
/**
* @throws GuzzleException
*/
function request($req_method , string $endpoint, array $data = [], HttpServiceConfigBean $configBean = null): HttpServiceReturnLogBean|bool
{
try {
if(!in_array($req_method, [self::REQ_METHOD_GET, self::REQ_METHOD_POST])) {
throw new \Exception('request method not support');
}
if ($configBean === null) $configBean = new HttpServiceConfigBean();
$req_data = [];
if($req_method === self::REQ_METHOD_GET) {
$req_data = ['query' => $data];
}
if($req_method === self::REQ_METHOD_POST) {
$req_data = ['json' => $data];
}
$resp = $this->getClient()->request($req_method,$endpoint, $req_data);
$status_code = $resp->getStatusCode();
$body = $resp->getBody()->getContents();
$resp->getBody()->close();
//记录日志
$oHttpServiceReturnLogBean = new HttpServiceReturnLogBean();
$oHttpServiceReturnLogBean->setRequestData($data);
$oHttpServiceReturnLogBean->setRequestUrl($endpoint);
$oHttpServiceReturnLogBean->setResponseStatusCode($status_code);
$oHttpServiceReturnLogBean->setResponseBody($body);
Logs::InfoLog(__CLASS__ . '-' . __FUNCTION__, $oHttpServiceReturnLogBean->toArrayNotNull());
return $oHttpServiceReturnLogBean;
}catch (\Exception $e) {
Logs::ErrLog(__CLASS__ . '-' . __FUNCTION__, $e, func_get_args());
return false;
}
}
}