Files
2026-03-11 18:24:59 +08:00

80 lines
2.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\common\service;
use think\Exception;
class HttpService
{
/**
* 发送HTTP请求
*/
public function request(string $url, string $method = 'GET', array $data = [], array $headers = [])
{
$method = strtoupper($method);
$curl = curl_init();
// 设置默认headers
$defaultHeaders = [
'Content-Type: application/json',
];
$headers = array_merge($defaultHeaders, $headers);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
// 根据环境判断是否禁用SSL验证
if (app()->env->get('app_env') !== 'production') {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
// 设置请求头
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// 根据请求方法设置
if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
}
} elseif (in_array($method, ['PUT', 'DELETE', 'PATCH'])) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
}
}
$response = curl_exec($curl);
$error = curl_error($curl);
$errno = curl_errno($curl);
curl_close($curl);
if ($errno) {
throw new Exception('HTTP请求失败: ' . $error . ' (错误码: ' . $errno . ')');
}
$result = json_decode($response, true);
// 如果JSON解析失败返回原始响应
if (json_last_error() !== JSON_ERROR_NONE) {
return $response;
}
return $result ?: $response;
}
/**
* 发送JSON请求简化方法
*/
public function json(string $url, string $method = 'GET', array $data = [])
{
$headers = [
'Content-Type: application/json',
'Accept: application/json',
];
return $this->request($url, $method, $data, $headers);
}
}