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); } }