| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace common\components\delivery\helpers;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\RequestException;
- use Yii;
- class HttpClient
- {
- /**
- * 发送 POST 请求(支持 JSON 自动解析 + 重试)
- */
- public static function post(string $url, array $data = [], array $headers = [], int $retry = 1)
- {
- $client = new Client([
- 'timeout' => 8.0,
- 'verify' => false, // 禁用 SSL 证书验证(测试环境可用)
- ]);
- $headers = array_merge([
- 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
- ], $headers);
- $body = http_build_query($data);
- for ($i = 0; $i <= $retry; $i++) {
- try {
- $response = $client->post($url, [
- 'headers' => $headers,
- 'body' => $body,
- ]);
- $status = $response->getStatusCode();
- $respBody = (string) $response->getBody();
- Yii::info("[HttpClient] POST {$url} {$status} {$respBody}");
- $json = json_decode($respBody, true);
- return $json ?: ['code' => $status, 'body' => $respBody];
- } catch (RequestException $e) {
- $message = $e->getMessage();
- Yii::error("[HttpClient] POST {$url} failed: {$message}");
- if ($i < $retry) {
- sleep(1); // 重试间隔
- continue;
- }
- return ['code' => 500, 'error' => $message];
- }
- }
- }
- /**
- * 发送 GET 请求
- */
- public static function get(string $url, array $params = [], array $headers = [], int $retry = 1)
- {
- $client = new Client([
- 'timeout' => 8.0,
- 'verify' => false,
- ]);
- $headers = array_merge([
- 'Accept' => 'application/json',
- ], $headers);
- for ($i = 0; $i <= $retry; $i++) {
- try {
- $response = $client->get($url, [
- 'headers' => $headers,
- 'query' => $params,
- ]);
- $status = $response->getStatusCode();
- $respBody = (string) $response->getBody();
- Yii::info("[HttpClient] GET {$url} {$status} {$respBody}");
- $json = json_decode($respBody, true);
- return $json ?: ['code' => $status, 'body' => $respBody];
- } catch (RequestException $e) {
- Yii::error("[HttpClient] GET {$url} failed: {$e->getMessage()}");
- if ($i < $retry) {
- sleep(1);
- continue;
- }
- return ['code' => 500, 'error' => $e->getMessage()];
- }
- }
- }
- }
|