89 lines
2.9 KiB
PHP
89 lines
2.9 KiB
PHP
<?php
|
||
|
||
namespace Tests;
|
||
|
||
use GuzzleHttp\Client;
|
||
use GuzzleHttp\Exception\RequestException;
|
||
|
||
class HttpBase
|
||
{
|
||
// 单例复用 HTTP 客户端
|
||
protected static $client = null;
|
||
|
||
/**
|
||
* 获取 Guzzle 客户端(支持动态设置 base_uri)
|
||
*
|
||
* @param string|null $baseUri
|
||
* @return Client
|
||
*/
|
||
protected static function get_client($baseUri = null)
|
||
{
|
||
if (self::$client === null) {
|
||
self::$client = new Client([
|
||
'timeout' => 60, // 设置请求超时时间为60秒
|
||
'connect_timeout' => 30, // 设置连接超时时间为30秒
|
||
'curl' => [
|
||
CURLOPT_FRESH_CONNECT => false,
|
||
CURLOPT_FORBID_REUSE => false,
|
||
],
|
||
'headers' => [
|
||
'Connection' => 'keep-alive',
|
||
'Accept' => 'application/json',
|
||
],
|
||
'base_uri' => $baseUri ?? 'http://127.0.0.1:8787',
|
||
]);
|
||
}
|
||
return self::$client;
|
||
}
|
||
|
||
/**
|
||
* 发送 HTTP 请求 (支持 JSON 和 FORM)
|
||
*
|
||
* @param array $data 请求数据
|
||
* @param string $url 请求地址(不包括 base_uri)
|
||
* @param string $method 请求方法(GET/POST)
|
||
* @param string|null $baseUri 动态设置 baseUri(可选)
|
||
* @param string $contentType 数据格式(json/form)
|
||
* @return array|false 响应的 JSON 数据或 false
|
||
*/
|
||
public static function httpclient($data, $url, $method = 'POST', $baseUri = null, $contentType = 'json')
|
||
{
|
||
$client = self::get_client($baseUri);
|
||
|
||
try {
|
||
$options = [];
|
||
|
||
if (strtoupper($method) === 'GET') {
|
||
// GET 请求将数据作为查询参数
|
||
$options['query'] = $data;
|
||
} else {
|
||
if ($contentType === 'json') {
|
||
// 发送 JSON 格式的数据
|
||
$options['json'] = $data;
|
||
} elseif ($contentType === 'form') {
|
||
// 发送 form-data 格式的数据
|
||
$options['form_params'] = $data;
|
||
}
|
||
}
|
||
|
||
// 发送请求
|
||
$response = $client->request(strtoupper($method), $url, $options);
|
||
|
||
// 解析 JSON 响应
|
||
$body = $response->getBody()->getContents();
|
||
return json_decode($body, true);
|
||
} catch (RequestException $e) {
|
||
// echo "HTTP 请求失败: " . $e->getMessage() . "\n";
|
||
if ($e->hasResponse()) {
|
||
$response = $e->getResponse();
|
||
$statusCode = $response->getStatusCode(); // 获取 HTTP 状态码
|
||
$body = $response->getBody()->getContents(); // 获取响应体
|
||
|
||
// echo "状态码: " . $statusCode . "\n";
|
||
// echo "响应体: " . $body . "\n";
|
||
}
|
||
return $statusCode;
|
||
}
|
||
}
|
||
}
|