123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- <?php
- namespace crmeb\services;
- class HttpService
- {
-
- private static $curlError;
-
- private static $headerStr;
-
- private static $status;
-
- public static function getCurlError()
- {
- return self::$curlError;
- }
-
- public static function getStatus()
- {
- return self::$status;
- }
-
- public static function getRequest($url, $data = array(), $header = false, $timeout = 10)
- {
- if (!empty($data)) {
- $url .= (stripos($url, '?') === false ? '?' : '&');
- $url .= (is_array($data) ? http_build_query($data) : $data);
- }
- return self::request($url, 'get', array(), $header, $timeout);
- }
-
- public static function request($url, $method = 'get', $data = array(), $header = false, $timeout = 15)
- {
- self::$status = null;
- self::$curlError = null;
- self::$headerStr = null;
- $curl = curl_init($url);
- $method = strtoupper($method);
-
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
-
- if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
-
- curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
-
- if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
- curl_setopt($curl, CURLOPT_FAILONERROR, false);
-
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
-
- curl_setopt($curl, CURLOPT_HEADER, true);
-
- curl_setopt($curl, CURLINFO_HEADER_OUT, true);
-
- if (1 == strpos("$" . $url, "https://")) {
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
- }
- self::$curlError = curl_error($curl);
- [$content, $status] = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
- self::$status = $status;
- self::$headerStr = trim(substr($content, 0, $status['header_size']));
- $content = trim(substr($content, $status['header_size']));
- return (intval($status["http_code"]) === 200) ? $content : false;
- }
-
- public static function postRequest($url, $data = [], $header = false, $timeout = 10)
- {
- return self::request($url, 'post', $data, $header, $timeout);
- }
-
- public static function getHeaderStr()
- {
- return self::$headerStr;
- }
-
- public static function getHeader()
- {
- $headArr = explode("\r\n", self::$headerStr);
- return $headArr;
- }
- }
|