美文网首页
PHP 使用curl进行GET和POST请求的封装

PHP 使用curl进行GET和POST请求的封装

作者: 贝尔特伦 | 来源:发表于2018-09-14 18:26 被阅读29次

    1,GET请求

    /**
     *  GET
     */
    public  function php_do_Url_GET($url,$params){
    
        $url = "{$url}?" . http_build_query ( $params );
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
    
        return $result;
    }
    

    2,POST请求

    /**
    * POST
    */
    public  function  php_do_url_POST($url,$params,$headers){
    
        $ch = curl_init ();
    
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
    
        $result = curl_exec ( $ch );
        curl_close ( $ch );
    
        return $result;
    }
    

    3,heaer中Content-Type注意事项

        //application/x-www-form-urlencoded 格式请求转http_build_query
    
        $postData = http_build_query($params);
        //application/json;charset=utf-8 请求转json_encode
        $jsonparams=json_encode($params);
    

    4,使用实例 post实例

     $url = "http://api.cn.ronghub.com/user/getToken.json";
        $params = array("userId"=>$userId,"name"=>$name,"portraitUri"=>$portraitUri);
        //application/x-www-form-urlencoded 格式请求转http_build_query
    
        $postData = http_build_query($params);
        //application/json;charset=utf-8 请求转json_encode
    //        $jsonparams=json_encode($params);
        $headers=array(
    
            "Content-Type: application/x-www-form-urlencoded",
            "Timestamp: " . $timestamp,
            "App-Key: " . $appKey,
            "Nonce: " . $nonce,
            "Signature:".$local_signature,
            'Content-Length: ' . strlen($postData)
        );
    
        $requestObj = new PhpUrlReqest();
        $result = $requestObj->php_do_url_POST($url,$postData,$headers);

    相关文章

      网友评论

          本文标题:PHP 使用curl进行GET和POST请求的封装

          本文链接:https://www.haomeiwen.com/subject/amqagftx.html