Exemplo n.º 1
0
 /**
  * @param $url
  * @param string $method
  * @param null $content
  * @param null $headers
  * @param bool $followLoc
  * @return CurlResponse
  */
 private function execCurl($url, $method = 'GET', $content = null, $headers = null, $followLoc = true)
 {
     $res = new CurlResponse();
     if (isset($method)) {
         curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
     }
     curl_setopt($this->ch, CURLOPT_URL, $url);
     curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout);
     if (!empty($headers)) {
         curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
     }
     curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $followLoc ? 1 : 0);
     //支持跳转
     //curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($res,'handleHeader')); // handle received headers
     curl_setopt($this->ch, CURLOPT_HEADER, true);
     if (!empty($content)) {
         $content_type = '';
         // 取content-type
         foreach ($headers as $h) {
             list($n, $v) = explode(':', $h) + array(null, null);
             if (strcasecmp(trim($n), 'Content-Type') === 0) {
                 $content_type = trim($v);
                 break;
             }
         }
         if (is_array($content) && $content_type == 'application/json') {
             curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($content));
         } else {
             if ($content_type == 'multipart/form-data') {
                 curl_setopt($this->ch, CURLOPT_POSTFIELDS, $content);
             } else {
                 if (is_array($content)) {
                     curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($content));
                 } else {
                     curl_setopt($this->ch, CURLOPT_POSTFIELDS, $content);
                 }
             }
         }
     }
     $response = curl_exec($this->ch);
     $res->http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
     $res->errno = curl_errno($this->ch);
     $res->errstr = curl_error($this->ch);
     $res->parseReturnData($response);
     return $res;
 }