访客地图

一个HTTP简单请求类

张成
2016/3

Class HttpRequest
{

    public $connect_timeout=10;
    public $timeout = 10;

    public function get($url,$params,$debug = false)
    {
        return $this->OAuthRequest($url,'GET',$params,$debug);
    }

    public function post($url,$params,$debug = false)
    {
        return $this->OAuthRequest($url,'POST',$params,$debug);
    }
    
    /**
     * 设置请求参数
     *
     * @param $url
     * @param $method
     * @param $params
     *
     * @return mixed
     */
    function OAuthRequest($url,$method,$params,$debug = false)
    {

        switch($method){
            case 'GET':
                $url = $url.'?'.http_build_query($params);
                return $this->http($url,'GET',NULL,NULL,$debug);
            default:
                $headers = array();
                $body = $params;
                return $this->http($url, $method, http_build_query($body), $headers,$debug);

        }
    }


    function http($url, $method, $postfields = NULL, $headers = array(),$debug = false)
    {
        $this->http_info = array();
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);
        curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        curl_setopt($ci, CURLOPT_HEADER, FALSE);

        switch($method){
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($postfields)) {

                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                }
                break;
            case 'GET':
                break;
        }

        curl_setopt($ci, CURLOPT_URL, $url );
        if(empty($headers)){
            $headers = array();
        }
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );

        $response = curl_exec($ci);
        $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $this->http_info = array_merge($this->http_info, curl_getinfo($ci));


        if ($this->debug || $debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);

            echo "=====headers======\r\n";
            print_r($headers);

            echo '=====request info====='."\r\n";
            print_r( curl_getinfo($ci) );

            echo '=====response====='."\r\n";
            print_r( $response );
        }
        curl_close ($ci);

        return $response;
    }


}