Пример #1
0
 public static function http_client($url, $method = 'GET', $fields)
 {
     $method = strtoupper($method);
     if (!self::_is_url($url)) {
         self::$error = "You have requested URL ({$url}) is not a valid HTTP address";
         return false;
     }
     // 如果是 get 方式,直接拼凑一个 url 出来
     if ($method == 'GET' && !empty($fields)) {
         $url = $url . (strpos($url, "?") === false ? "?" : "&") . http_build_query($fields);
     }
     $parse_url = parse_url($url);
     if (empty($parse_url) || empty($parse_url['host']) || !in_array($parse_url['scheme'], array('http', 'https'))) {
         self::$error = "No connection adapters were found for '{$url}'";
         return false;
     }
     $scheme = $parse_url['scheme'];
     $domain = $parse_url['host'];
     // 随机绑定 hosts,做负载均衡
     //if (self::$hosts)
     //{
     //$host = $parse_url['host'];
     //$key = rand(0, count(self::$hosts)-1);
     //$ip = self::$hosts[$key];
     //$url = str_replace($host, $ip, $url);
     //self::$headers['Host'] = $host;
     //}
     curl_setopt(self::$ch, CURLOPT_URL, $url);
     if ($method != 'GET') {
         // 如果是 post 方式
         if ($method == 'POST') {
             curl_setopt(self::$ch, CURLOPT_POST, true);
         } else {
             self::$headers['X-HTTP-Method-Override'] = $method;
             curl_setopt(self::$ch, CURLOPT_CUSTOMREQUEST, $method);
         }
         curl_setopt(self::$ch, CURLOPT_POSTFIELDS, $fields);
     }
     $cookies = self::get_cookies();
     $domain_cookies = self::get_cookies($domain);
     $cookies = array_merge($cookies, $domain_cookies);
     // 是否设置了cookie
     if (!empty($cookies)) {
         foreach ($cookies as $key => $value) {
             $cookie_arr[] = $key . "=" . $value;
         }
         $cookies = implode("; ", $cookie_arr);
         curl_setopt(self::$ch, CURLOPT_COOKIE, $cookies);
     }
     if (self::$headers) {
         $headers = array();
         foreach (self::$headers as $k => $v) {
             $headers[] = $k . ": " . $v;
         }
         curl_setopt(self::$ch, CURLOPT_HTTPHEADER, $headers);
     }
     curl_setopt(self::$ch, CURLOPT_ENCODING, 'gzip');
     if (self::$proxies) {
         if (!empty(self::$proxies[$scheme])) {
             curl_setopt(self::$ch, CURLOPT_PROXY, self::$proxies[$scheme]);
         }
     }
     // header + body,header 里面有 cookie
     curl_setopt(self::$ch, CURLOPT_HEADER, true);
     self::$raw = curl_exec(self::$ch);
     //var_dump($data);
     self::$info = curl_getinfo(self::$ch);
     self::$status_code = self::$info['http_code'];
     if (self::$raw === false) {
         self::$error = ' Curl error: ' . curl_error(self::$ch);
     }
     // 关闭句柄
     curl_close(self::$ch);
     // 请求成功之后才把URL存起来
     self::$url = $url;
     self::$content = self::get_response_body($domain);
     //$data = substr($data, 10);
     //$data = gzinflate($data);
     return self::$content;
 }