91 lines
2.1 KiB
PHP
91 lines
2.1 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Helper;
|
||
|
||
use App\Exception\BusinessException;
|
||
use GuzzleHttp\Client;
|
||
use Hyperf\Guzzle\HandlerStackFactory;
|
||
|
||
/**
|
||
* 请求处理公共类
|
||
*/
|
||
class Curl
|
||
{
|
||
/**
|
||
* 获取Guzzle客户端实例(使用连接池)
|
||
*
|
||
* @return Client
|
||
*/
|
||
protected static function getClient() : Client
|
||
{
|
||
$factory = new HandlerStackFactory();
|
||
$stack = $factory->create();
|
||
|
||
return make(Client::class, [
|
||
'config' => [
|
||
'handler' => $stack,
|
||
]
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* 发送Get请求
|
||
*
|
||
* @param string $url
|
||
* @param array $headers
|
||
* @return array
|
||
*/
|
||
public static function get(string $url, array $headers = []) : array
|
||
{
|
||
$client = self::getClient();
|
||
$options = ['timeout' => 2, 'verify' => false];
|
||
|
||
if (!empty($headers)) {
|
||
$options['headers'] = $headers;
|
||
}
|
||
|
||
try {
|
||
$response = $client->get($url, $options);
|
||
} catch (\Throwable $throwable) {
|
||
throw new BusinessException($throwable->getCode(), $throwable->getMessage());
|
||
}
|
||
|
||
if ($response->getStatusCode() === 200) {
|
||
return json_decode($response->getBody()->getContents(), true);
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
/**
|
||
* 发送POST请求(application/x-www-form-urlencoded)
|
||
*
|
||
* @param string $url
|
||
* @param array $data
|
||
* @param array $headers
|
||
* @return array
|
||
*/
|
||
public static function post(string $url, array $data = [], array $headers = []) : array
|
||
{
|
||
$client = self::getClient();
|
||
$options = ['timeout' => 2, 'verify' => false, 'form_params' => $data];
|
||
|
||
if (!empty($headers)) {
|
||
$options['headers'] = $headers;
|
||
}
|
||
|
||
try {
|
||
$response = $client->post($url, $options);
|
||
} catch (\Throwable $throwable) {
|
||
throw new BusinessException($throwable->getCode(), $throwable->getMessage());
|
||
}
|
||
|
||
if ($response->getStatusCode() === 200) {
|
||
return json_decode($response->getBody()->getContents(), true);
|
||
}
|
||
|
||
return [];
|
||
}
|
||
} |