123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace app\utils;
- class CurlUtil{
- public static function getHttp($url,$ssl = true){
- $domain = $_SERVER['HTTP_HOST'];
- $http = 'http://';
- $ssl && $http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
- return $http.$domain.$url;
- }
- /**
- * 模拟http get请求
- * @param $url
- * @param array $params
- * @param array $header
- * @param int $timeout
- * @return bool|string
- * @throws \Exception
- */
- public static function get($url, $params=array(), $header = array(),$timeout=30){
- $opts = array(
- CURLOPT_TIMEOUT => $timeout,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTPHEADER => $header,
- CURLOPT_URL => count($params) > 0 ? $url . '?' . http_build_query($params) : $url,
- );
- $ch = curl_init();
- curl_setopt_array($ch, $opts);
- $data = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error)
- throw new \Exception('http get error:' . $error);
- return $data;
- }
- /**
- * 模拟http post请求
- * @param $url
- * @param $params
- * @param array $header
- * @param int $timeout
- * @return bool|string
- * @throws \Exception
- */
- public static function post($url, $params, $header = array(), $timeout=30){
- $opts = array(
- CURLOPT_TIMEOUT => $timeout,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTPHEADER => $header,
- CURLOPT_URL => $url,
- CURLOPT_POST => 1,
- CURLOPT_POSTFIELDS => is_array($params) ? http_build_query($params) : $params
- );
- $ch = curl_init();
- curl_setopt_array($ch, $opts);
- $data = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error)
- throw new \Exception('http post error:' . $error);
- return $data;
- }
- /**
- * 模拟http post json请求
- * @param string $url
- * @param array $params
- * @param array $header
- * @param int $timeout
- * @return bool|string
- * @throws \Exception
- */
- public static function postJson(string $url, array $params, array $header = [], int $timeout=30){
- $opts = [
- CURLOPT_TIMEOUT => $timeout,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTPHEADER => array_merge(["content-type:application/json"],$header),
- CURLOPT_URL => $url,
- CURLOPT_POST => 1,
- CURLOPT_POSTFIELDS => json_encode($params)
- ];
- $ch = curl_init();
- curl_setopt_array($ch, $opts);
- $data = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error)
- throw new \Exception('http post error:' . $error);
- return json_decode($data,true);
- }
- }
|