123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- declare(strict_types=1);
- namespace tdengine;
- /**
- * @method httpRequest
- */
- class TdUtils
- {
- // public static $curlHandler = null;
- /**
- * [http 调用接口函数]
- * @param string $url [接口地址]
- * @param array $params [数组]
- * @param string $method [GET\POST\DELETE\PUT]
- * @param array $header [HTTP头信息]
- * @param integer $timeout [超时时间] 秒
- * @return json_decode {"status":"error", "desc":"http url parse error"} or {"status":"succ","head":["affected_rows"],"data":[[2]],"rows":2}
- */
- public static function httpRequest($url, $params, $method = 'GET', $header = array(), $timeout = 2)
- {
- $curlHandler = curl_init();
- if (empty($curlHandler)) {
- $errJson['desc'] = "curl_init error";
- return $errJson;
- }
- // POST 提交方式的传入 $set_params 必须是字符串形式
- $opts = array(
- CURLOPT_TIMEOUT => $timeout,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTPHEADER => $header
- );
- $errJson['status'] = 'error';
- /* 根据请求类型设置特定参数 */
- switch (strtoupper($method)) {
- case 'GET':
- $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
- break;
- case 'POST':
- //$params = http_build_query($params);
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 1;
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- case 'DELETE':
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
- $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- case 'PUT':
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 0;
- $opts[CURLOPT_CUSTOMREQUEST] = 'PUT';
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- default:
- $errJson['desc'] = '不支持的请求方式';
- return $errJson;
- }
- if (empty(curl_setopt_array($curlHandler, $opts))) {
- $errJson['desc'] = "curl_setopt_array error";
- return $errJson;
- }
- $data = curl_exec($curlHandler);
-
- if (empty($data)) {
- $errJson['desc'] = curl_error($curlHandler);
- return $errJson;
- }
- // curl_close($curlHandler);
- // $curlHandler = null
- $res = json_decode($data, true);
- if (empty($res)) {
- $errJson['desc'] = "tdHttp request failed json_decode,val:{$data}";
- return $errJson;
- }
- return $res;
- }
- }
|