HttpClient.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace common\components\delivery\helpers;
  3. use GuzzleHttp\Client;
  4. use GuzzleHttp\Exception\RequestException;
  5. use Yii;
  6. class HttpClient
  7. {
  8. /**
  9. * 发送 POST 请求(支持 JSON 自动解析 + 重试)
  10. */
  11. public static function post(string $url, array $data = [], array $headers = [], int $retry = 1)
  12. {
  13. $client = new Client([
  14. 'timeout' => 8.0,
  15. 'verify' => false, // 禁用 SSL 证书验证(测试环境可用)
  16. ]);
  17. $headers = array_merge([
  18. 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
  19. ], $headers);
  20. $body = http_build_query($data);
  21. for ($i = 0; $i <= $retry; $i++) {
  22. try {
  23. $response = $client->post($url, [
  24. 'headers' => $headers,
  25. 'body' => $body,
  26. ]);
  27. $status = $response->getStatusCode();
  28. $respBody = (string) $response->getBody();
  29. Yii::info("[HttpClient] POST {$url} {$status} {$respBody}");
  30. $json = json_decode($respBody, true);
  31. return $json ?: ['code' => $status, 'body' => $respBody];
  32. } catch (RequestException $e) {
  33. $message = $e->getMessage();
  34. Yii::error("[HttpClient] POST {$url} failed: {$message}");
  35. if ($i < $retry) {
  36. sleep(1); // 重试间隔
  37. continue;
  38. }
  39. return ['code' => 500, 'error' => $message];
  40. }
  41. }
  42. }
  43. /**
  44. * 发送 GET 请求
  45. */
  46. public static function get(string $url, array $params = [], array $headers = [], int $retry = 1)
  47. {
  48. $client = new Client([
  49. 'timeout' => 8.0,
  50. 'verify' => false,
  51. ]);
  52. $headers = array_merge([
  53. 'Accept' => 'application/json',
  54. ], $headers);
  55. for ($i = 0; $i <= $retry; $i++) {
  56. try {
  57. $response = $client->get($url, [
  58. 'headers' => $headers,
  59. 'query' => $params,
  60. ]);
  61. $status = $response->getStatusCode();
  62. $respBody = (string) $response->getBody();
  63. Yii::info("[HttpClient] GET {$url} {$status} {$respBody}");
  64. $json = json_decode($respBody, true);
  65. return $json ?: ['code' => $status, 'body' => $respBody];
  66. } catch (RequestException $e) {
  67. Yii::error("[HttpClient] GET {$url} failed: {$e->getMessage()}");
  68. if ($i < $retry) {
  69. sleep(1);
  70. continue;
  71. }
  72. return ['code' => 500, 'error' => $e->getMessage()];
  73. }
  74. }
  75. }
  76. }