TdUtils.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. declare(strict_types=1);
  3. namespace tdengine;
  4. /**
  5. * @method httpRequest
  6. */
  7. class TdUtils
  8. {
  9. // public static $curlHandler = null;
  10. /**
  11. * [http 调用接口函数]
  12. * @param string $url [接口地址]
  13. * @param array $params [数组]
  14. * @param string $method [GET\POST\DELETE\PUT]
  15. * @param array $header [HTTP头信息]
  16. * @param integer $timeout [超时时间] 秒
  17. * @return json_decode {"status":"error", "desc":"http url parse error"} or {"status":"succ","head":["affected_rows"],"data":[[2]],"rows":2}
  18. */
  19. public static function httpRequest($url, $params, $method = 'GET', $header = array(), $timeout = 2)
  20. {
  21. $curlHandler = curl_init();
  22. if (empty($curlHandler)) {
  23. $errJson['desc'] = "curl_init error";
  24. return $errJson;
  25. }
  26. // POST 提交方式的传入 $set_params 必须是字符串形式
  27. $opts = array(
  28. CURLOPT_TIMEOUT => $timeout,
  29. CURLOPT_RETURNTRANSFER => 1,
  30. CURLOPT_SSL_VERIFYPEER => false,
  31. CURLOPT_SSL_VERIFYHOST => false,
  32. CURLOPT_HTTPHEADER => $header
  33. );
  34. $errJson['status'] = 'error';
  35. /* 根据请求类型设置特定参数 */
  36. switch (strtoupper($method)) {
  37. case 'GET':
  38. $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
  39. break;
  40. case 'POST':
  41. //$params = http_build_query($params);
  42. $opts[CURLOPT_URL] = $url;
  43. $opts[CURLOPT_POST] = 1;
  44. $opts[CURLOPT_POSTFIELDS] = $params;
  45. break;
  46. case 'DELETE':
  47. $opts[CURLOPT_URL] = $url;
  48. $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
  49. $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
  50. $opts[CURLOPT_POSTFIELDS] = $params;
  51. break;
  52. case 'PUT':
  53. $opts[CURLOPT_URL] = $url;
  54. $opts[CURLOPT_POST] = 0;
  55. $opts[CURLOPT_CUSTOMREQUEST] = 'PUT';
  56. $opts[CURLOPT_POSTFIELDS] = $params;
  57. break;
  58. default:
  59. $errJson['desc'] = '不支持的请求方式';
  60. return $errJson;
  61. }
  62. if (empty(curl_setopt_array($curlHandler, $opts))) {
  63. $errJson['desc'] = "curl_setopt_array error";
  64. return $errJson;
  65. }
  66. $data = curl_exec($curlHandler);
  67. if (empty($data)) {
  68. $errJson['desc'] = curl_error($curlHandler);
  69. return $errJson;
  70. }
  71. // curl_close($curlHandler);
  72. // $curlHandler = null
  73. $res = json_decode($data, true);
  74. if (empty($res)) {
  75. $errJson['desc'] = "tdHttp request failed json_decode,val:{$data}";
  76. return $errJson;
  77. }
  78. return $res;
  79. }
  80. }