zoukankan      html  css  js  c++  java
  • php用curl调用接口方法,get和post两种方式

    首先是客户端执行方法ApiModel.php:

    <?php 
    /**
         * 模拟post进行url请求
         * @param string $url
         * @param array $post_data
         */
        function request_post($url = '',$ispost=true, $post_data = array()) {
            if (empty($url) || empty($post_data)) {
                return false;
            }
            
            $o = "";
            foreach ( $post_data as $k => $v ) 
            { 
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
            $key=md5(base64_encode($post_data));
            if($ispost){
                $url=$url;
            }else{
                $url = $url.'?'.$post_data;
            }
            
           
            $curlPost = 'key='.$key;
            header("Content-type: text/html; charset=utf-8");
            $ch = curl_init();//初始化curl
            curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            if($ispost){
                curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
                curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            }
            $data = curl_exec($ch);//运行curl
            curl_close($ch);
            return $data;
        }
        ?>

    客户端调用方法,可以在此配置基本信息api.php:

    <?php 
    require 'ApiModel.php';
    function testAction(){
            $url = '接口地址';
            $post_data['appid']       = '10';
            $post_data['appkey']      = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';
            $post_data['member_name'] = 'zsjs124';
            $post_data['password']    = '123456';
            $post_data['email']    = 'zsjs124@126.com';
            //$post_data = array();
            $res = request_post($url,$ispost=true,$post_data);       
            print_r($res);
    
        }
    testAction();
    ?>

    服务器的接口函数test.php:

    <?php 
    function serverapi(){
        $key='57173d6ad842d807443ee0db91fed323';
        if($_GET&&$_GET['appkey']=='cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ'||$_POST&&$_POST['key']===$key){
            $arr=array('name'=>'huanglu','password'=>'123456');
            echo json_encode($arr);
        }else{
            exit('非法访问!');
        }
    }
    serverapi();
    ?>
  • 相关阅读:
    应用环境配置记录
    【C#】Dictionary通过value获取对应的key值
    DevExpress 之 GridControl 自定义列(转)
    C#中gridView常用属性和技巧介绍(转)
    【643】cv2.imread() 函数
    【642】Python 实现膨胀、腐蚀、提取边线
    【639】keras 中 fit_generator 的 数据生成器
    【638】keras 多输出模型【实战】
    【637】一个图片两个标注的图像增强
    别自嗨了!想做新生代农民工,你还不够格。。
  • 原文地址:https://www.cnblogs.com/hltswd/p/5638453.html
Copyright © 2011-2022 走看看