HttpClient.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // 根据 Content-Type 决定请求体格式
  21. if (strpos($headers['Content-Type'], 'application/json') !== false) {
  22. $body = json_encode($data);
  23. } else {
  24. $body = http_build_query($data);
  25. }
  26. for ($i = 0; $i <= $retry; $i++) {
  27. try {
  28. $response = $client->post($url, [
  29. 'headers' => $headers,
  30. 'body' => $body
  31. ]);
  32. $status = $response->getStatusCode();
  33. $respBody = (string) $response->getBody();
  34. Yii::info("[HttpClient] POST {$url} {$status} {$respBody}");
  35. $json = json_decode($respBody, true);
  36. return $json ?: ['code' => $status, 'body' => $respBody];
  37. } catch (RequestException $e) {
  38. $message = $e->getMessage();
  39. Yii::error("[HttpClient] POST {$url} failed: {$message}");
  40. if ($i < $retry) {
  41. sleep(1); // 重试间隔
  42. continue;
  43. }
  44. return ['code' => 500, 'error' => $message];
  45. }
  46. }
  47. }
  48. /**
  49. * 发送 GET 请求
  50. */
  51. public static function get(string $url, array $params = [], array $headers = [], int $retry = 1)
  52. {
  53. $client = new Client([
  54. 'timeout' => 8.0,
  55. 'verify' => false,
  56. ]);
  57. $headers = array_merge([
  58. 'Accept' => 'application/json',
  59. ], $headers);
  60. for ($i = 0; $i <= $retry; $i++) {
  61. try {
  62. $response = $client->get($url, [
  63. 'headers' => $headers,
  64. 'query' => $params,
  65. ]);
  66. $status = $response->getStatusCode();
  67. $respBody = (string) $response->getBody();
  68. Yii::info("[HttpClient] GET {$url} {$status} {$respBody}");
  69. $json = json_decode($respBody, true);
  70. return $json ?: ['code' => $status, 'body' => $respBody];
  71. } catch (RequestException $e) {
  72. Yii::error("[HttpClient] GET {$url} failed: {$e->getMessage()}");
  73. if ($i < $retry) {
  74. sleep(1);
  75. continue;
  76. }
  77. return ['code' => 500, 'error' => $e->getMessage()];
  78. }
  79. }
  80. }
  81. }