PHP中调用接口

引用:http://zhidao.baidu.com/question/454935450.html&__bd_tkn__=67bd5d3a742a8b244e09a86fb8b824aa950c9efd8078338d51fed8133ea5c69d362ad36bb4bcda3b39bb3949f6bbe47087ac3af56e60b1f4e7eb60157c59f93b9e62adfd5e0f03de01252778a636bc0c4a739c050b5fbd8ed149437d742a3220cb647f3449c2aba89e0ef9accbdc8c0bc23026f14aa0

如:
http://localhost/operate.php?act=get_user_list&type=json

在这里operate.php相当于一个接口,其中get_user_list 是一个API(获取用户列表),讲求返回的数据类型为JSON格式。

你只需要在你PHP代码中执行这条链接他就会返回。
GET方式的直接使用 
$file_contents = file_get_contents('http://localhost/operate.php?act=get_user_list&type=json') 

POST方式得用下面的(需要开启PHP curl支持)。 
$url = 'http://localhost/operate.php?act=get_user_list&type=json';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt ( $ch, CURLOPT_POST, 1 ); //启用POST提交
$file_contents = curl_exec ( $ch );
curl_close ( $ch );

方法1:用file_get_contents以get方式获取内容 <?php $url=’http://www.zhoz.com/’; $html=file_get_contents($url); //print_r($http_response_header); ec($html); printhr(); printarr($http_response_header); printhr(); ?> 
 
方法2:用fopen打开url,以get方式获取内容 我觉得这个方法比较常用。 <?php $fp=fopen($url,‘r’); printarr(stream_get_meta_data($fp)); printhr(); while(!feof($fp)){ $result.=fgets($fp,1024); } echo"urlbody:$result"; printhr(); fclose($fp); ?> 
 
方法3:用file_get_contents函数,以post方式获取url <?php $data=array(’foo’=>‘bar’); $data=http_build_query($data); $opts=array( ‘http’=>array( ‘method’=>‘POST’, ‘header’=>"Content-type:application/x-www-form-urlencoded ". "Content-Length:".strlen($data)." ", ‘content’=>$data ), ); $context=stream_context_create($opts); $html=file_get_contents(’http://localhost/e/admin/test.html’,false,$context); echo$html; ?> 
 
方法4:用fsockopen函数打开url,以get方式获取完整的数据,包括header和body <?php functionget_url($url,$cookie=false){ $url=parse_url($url); $query=$url[path]."?".$url[query]; ec("Query:".$query); $fp=fsockopen($url[host],$url[port]?$url[port]:80,$errno,$errstr,30); if(!$fp){ returnfalse; }else{ $request="GET$queryHTTP/1.1 "; $request.="Host:$url[host] "; $request.="Connection:Close "; if($cookie)$request.="Cookie:$cookie "; $request.=" "; fwrite($fp,$request); while(!@feof($fp)){ $result.=@fgets($fp,1024); } fclose($fp); return$result; } } //获取url的html部分,去掉header functionGetUrlHTML($url,$cookie=false){ $rowdata=get_url($url,$cookie); if($rowdata) { $body=stristr($rowdata," "); $body=substr($body,4,strlen($body)); return$body; } returnfalse; } ?> 
 
方法5:用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body <?php functionHTTP_Post($URL,$data,$cookie,$referrer=""){ //parsingthegivenURL $URL_Info=parse_url($URL); //Buildingreferrer if($referrer=="")//ifnotgivenusethisscriptasreferrer $referrer="111"; //makingstringfrom$data foreach($dataas$key=>$value) $values[]="$key=".urlencode($value); $data_string=implode("&",$values); //Findoutwhichportisneeded–ifnotgivenusestandard(=80) if(!isset($URL_Info["port"])) $URL_Info["port"]=80; //buildingPOST-request: $request.="POST".$URL_Info["path"]."HTTP/1.1 "; $request.="Host:".$URL_Info["host"]." "; $request.="Referer:$referer "; $request.="Content-type:application/x-www-form-urlencoded "; $request.="Content-length:".strlen($data_string)." "; $request.="Connection:close "; $request.="Cookie:$cookie "; $request.=" "; $request.=$data_string." "; $fp=fsockopen($URL_Info["host"],$URL_Info["port"]); fputs($fp,$request); while(!feof($fp)){ $result.=fgets($fp,1024); } fclose($fp); return$result; } printhr(); ?> 
 
方法6:使用curl库,使用curl库之前,你可能需要查看一下php.ini,查看是否已经打开了curl扩展 <?php $ch=curl_init(); $timeout=5; curl_setopt($ch,CURLOPT_URL,‘http://www.zhoz.com/’); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $file_contents=curl_exec($ch); curl_close($ch); echo$file_contents; ?> 关于curl库: curl官方网站http://curl.haxx.se/ curl是使用URL语法的传送文件工具,支持FTP、FTPS、HTTPHTPPSSCPSFTPTFTPTELNETDICTFILE和LDAP。curl支持SSL证书、HTTPPOST、HTTPPUT、FTP上传,kerberos、基于HTT格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道和大量其他有用的技巧,最近热门的SNS中也用到这个方法,取得MSN上的好友列表等,应用还是挺多的。只不过需要组件支持,开启方法我的技术圈中有说明:http://o.zhoz.com/ <?php functionprintarr(array$arr) { echo"
Rowfieldcount:".count($arr)."
"; foreach($arras$key=>$value) { echo"$key=$value
"; } } ?>
 
 
 
 
复制代码
 /**
     * 模拟post进行url请求
     * @param string $url
     * @param string $param
     */
    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }
复制代码

这是方法,

下面是具体的调用案例。

复制代码
    function testAction(){
        $url = 'http://mobile.jschina.com.cn/jschina/register.php';
        $post_data['appid']       = '10';
        $post_data['appkey']      = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';
        $post_data['member_name'] = 'zsjs123';
        $post_data['password']    = '123456';
        $post_data['email']    = 'zsjs123@126.com';
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $res = $this->request_post($url, $post_data);       
        print_r($res);

    }
复制代码

这样就提交请求,并且获取请求结果了。一般返回的结果是json格式的。

这里的post是拼接出来的。

也可以改造成下面的方式。

复制代码
/**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    function request_post($url = '', $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);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }
复制代码

将拼接也封装了起来,这样调用的时候就更简洁了。

复制代码
function testAction(){
        $url = 'http://mobile.jschina.com.cn/jschina/register.php';
        $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 = $this->request_post($url, $post_data);       
        print_r($res);

    }
复制代码
原文地址:https://www.cnblogs.com/bluealine/p/6078481.html