feat: 添加了 http 请求服务

This commit is contained in:
李东云
2023-03-13 16:14:22 +08:00
parent e33c115938
commit 7c1efe1a1f
5 changed files with 174 additions and 7 deletions

View File

@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Singularity\HDK\Core\Service;
use Ergebnis\Http\Method;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Utils\Codec\Json;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* 发起 Http 请求的类
*/
class HttpRequestService
{
public const TIMEOUT = 20;
/**
* @Inject()
* @var ClientFactory
*/
private ClientFactory $client;
/**
* @var array<literal-string, mixed>
*/
private array $options = [];
/**
* @throws GuzzleException
* @throws ClientExceptionInterface
*/
public function requestGet(string $url, array $params = []): ResponseInterface
{
$request = new Request(Method\Rfc\Rfc7231::GET, $url);
return $this->getClient()->send($request, [
'params' => $params,
]);
}
private function getClient(): Client
{
return $this->client->create($this->options);
}
/**
* @param string $url
* @param array $data
* @param array $params
* @return ResponseInterface
* @throws GuzzleException
*/
public function requestPost(string $url, string $data = '', array $params = []): ResponseInterface
{
$request = new Request('post', $url, [], $data);
return $this->getClient()->send($request, [
'params' => $params,
]);
}
/**
* @param string $url
* @param array $data
* @param array $params
* @return ResponseInterface
* @throws GuzzleException
*/
public function requestPut(string $url, array $data = [], array $params = []): ResponseInterface
{
$data = Json::encode($data);
$request = new Request('put', $url, ['Content-Type' => 'application/json'], Utils::streamFor($data));
$result = $this->getClient()->send($request, [
'params' => $params,
]);
$json = Json::decode($result->getBody()->getContents());
if ($json['code'] !== 200) {
throw new ServerException($json['message'], $request, $result);
}
return $result;
}
/**
* 定制 options
* @param array $options
* @return $this
*/
public function setOptions(array $options): HttpRequestService
{
$this->options = array_replace_recursive($this->options, $options);
return $this;
}
/**
* @param ResponseInterface $response
* @param RequestInterface $request
* @return ResponseInterface
*/
private function parseResponse(
ResponseInterface $response,
RequestInterface $request
): ResponseInterface {
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
return $response;
} else {
throw new BadResponseException($response->getReasonPhrase(), $request, $response);
}
}
}