mirror of
http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore.git
synced 2026-01-15 07:15:06 +08:00
102 lines
2.6 KiB
PHP
102 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Singularity\HDK\Core\Service;
|
|
|
|
use Ergebnis\Http\Method;
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Exception\GuzzleException;
|
|
use GuzzleHttp\Psr7\Request;
|
|
use GuzzleHttp\Psr7\Utils;
|
|
use Hyperf\Codec\Json;
|
|
use Hyperf\Di\Annotation\Inject;
|
|
use Hyperf\Guzzle\ClientFactory;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
|
|
/**
|
|
* 发起 Http 请求的类
|
|
*/
|
|
class HttpRequestService
|
|
{
|
|
// public const TIMEOUT = 20;
|
|
|
|
#[Inject]
|
|
private ClientFactory $client;
|
|
|
|
/**
|
|
* @var array<literal-string, mixed>
|
|
*/
|
|
private array $options = [];
|
|
|
|
/**
|
|
* @param string $url
|
|
* @param array<string, string|int> $params
|
|
* @param array $data
|
|
* @return ResponseInterface
|
|
* @throws GuzzleException
|
|
*/
|
|
public function requestGet(string $url, array $params = [], array $data = []): ResponseInterface
|
|
{
|
|
$request = new Request(Method\Rfc\Rfc7231::GET, $url);
|
|
return $this->getClient()->send($request, [
|
|
'query' => $params,
|
|
'json' => $data,
|
|
]);
|
|
}
|
|
|
|
private function getClient(): Client
|
|
{
|
|
return $this->client->create($this->options);
|
|
}
|
|
|
|
/**
|
|
* @param string $url
|
|
* @param array<string, mixed> $data
|
|
* @param array<string, string|int> $params
|
|
* @return ResponseInterface
|
|
* @throws GuzzleException
|
|
*/
|
|
public function requestPost(string $url, array $params = [], array $data = []): ResponseInterface
|
|
{
|
|
$data = Json::encode($data);
|
|
$request = new Request(
|
|
'post',
|
|
$url,
|
|
['Content-Type' => 'application/json'],
|
|
Utils::streamFor($data),
|
|
);
|
|
return $this->getClient()->send($request, [
|
|
'query' => $params,
|
|
]);
|
|
}
|
|
|
|
|
|
/**
|
|
* @param string $url
|
|
* @param array<string, mixed> $data
|
|
* @param array<string, string|int> $params
|
|
* @return ResponseInterface
|
|
* @throws GuzzleException
|
|
*/
|
|
public function requestPut(string $url, array $params = [], array $data = []): ResponseInterface
|
|
{
|
|
$data = Json::encode($data);
|
|
$request = new Request('put', $url, ['Content-Type' => 'application/json'], Utils::streamFor($data));
|
|
return $this->getClient()->send($request, [
|
|
'query' => $params,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 定制 options
|
|
* @param array<string, mixed> $options
|
|
* @return $this
|
|
*/
|
|
public function setOptions(array $options): HttpRequestService
|
|
{
|
|
$this->options = array_replace_recursive($this->options, $options);
|
|
return $this;
|
|
}
|
|
}
|