引用: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\r\n". "Content-Length:".strlen($data)."\r\n", ‘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\r\n"; $request.="Host:$url[host]\r\n"; $request.="Connection:Close\r\n"; if($cookie)$request.="Cookie:$cookie\n"; $request.="\r\n"; 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,"\r\n\r\n"); $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\n"; $request.="Host:".$URL_Info["host"]."\n"; $request.="Referer:$referer\n"; $request.="Content-type:application/x-www-form-urlencoded\n"; $request.="Content-length:".strlen($data_string)."\n"; $request.="Connection:close\n"; $request.="Cookie:$cookie\n"; $request.="\n"; $request.=$data_string."\n"; $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); }

PHP中调用接口的更多相关文章

  1. 在网页程序或Java程序中调用接口实现短信猫收发短信的解决方案

    方案特点: 在网页程序或Java程序中调用接口实现短信猫收发短信的解决方案,简化软件开发流程,减少各应用系统相同模块的重复开发工作,提高系统稳定性和可靠性. 基于HTTP协议的开发接口 使用特点在网页 ...

  2. api 接口开发理论 在php中调用接口以及编写接口

    如: http://localhost/openUser.php?act=get_user_list&type=json 在这里openUser.php相当于一个接口,其中get_user_l ...

  3. android 中调用接口发送短信

    android中可以通过两种方式发送短信 第一:调用系统短信接口直接发送短信:主要代码如下: //直接调用短信接口发短信 SmsManager smsManager = SmsManager.getD ...

  4. 在PHP中调用接口

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

  5. WebApi接口 - 如何在应用中调用webapi接口

    很高兴能再次和大家分享webapi接口的相关文章,本篇将要讲解的是如何在应用中调用webapi接口:对于大部分做内部管理系统及类似系统的朋友来说很少会去调用别人的接口,因此可能在这方面存在一些困惑,希 ...

  6. 在C代码中调用C++接口

    一 在C源文件中调用C++封装的接口 例如: 要想在A.c文件中,调用生命在B.h,实现在B.cpp中的接口bool getMAC(char *mac_addr); 其实现方法 B.cpp 如下: / ...

  7. AutoCAD.NET 不使用P/Invoke方式调用acad.exe或accore.dll中的接口(如acedCommand、acedPostCommand等)

    使用C#进行AutoCAD二次开发,有时候由于C#接口不够完善,或者低版本AutoCAD中的接口缺少,有些工作不能直接通过C#接口来实现,所以需要通过P/Invoke的方式调用AutoCAD的其他DL ...

  8. json格式数据,将数据库中查询的结果转换为json, 然后调用接口的方式返回json(方式一)

    调用接口,无非也就是打开链接 读取流 将结果以流的形式输出 将查询结果以json返回,无非就是将查询到的结果转换成jsonObject ================================ ...

  9. 在php中调用以及编写接口(转)

    如: http://localhost/openUser.php?act=get_user_list&type=json 在这里openUser.php相当于一个接口,其中get_user_l ...

随机推荐

  1. Spring技术笔记(一)

    一.控制反转(IoC)&依赖注入(DI) 1.控制反转: 所谓的控制反转就是应用本身不负责依赖对象的创建及维护, 依赖对象的创建及维护是由外部容器负责的. 这样控制权就由应用转移到了外部容器, ...

  2. EMI-CLK信号串电阻并电容

    一般DMIC的CLK都会EMI超标,所以看到的案子这个DMIC CLK信号都会源端串接电阻和并电容 1,串电阻是为了信号的完整性,考虑到匹配的,一般说来这个电阻不是固定的,要随实际的PCB的走线的阻抗 ...

  3. Spark源码分析之八:Task运行(二)

    在<Spark源码分析之七:Task运行(一)>一文中,我们详细叙述了Task运行的整体流程,最终Task被传输到Executor上,启动一个对应的TaskRunner线程,并且在线程池中 ...

  4. eclipse maven安装配置

      下载在Apache下载Maven,下载地址:http://maven.apache.org/download.html,在win7下载文件为:apache-maven-3.1.0-bin.zip. ...

  5. ndk javah配置

    Location: C:\Program Files\Java\jdk1.6.0_25\bin\javah.exe Working Directory: ${project_loc} Argument ...

  6. ASP.NET动态网站制作(10)-- JQ(2)

    前言:jq的第二节课. 内容: 1.管理选择结果:  (1)获取元素个数:$("img").size():获取页面中所有“img”个数:  (2)提取元素:$("img[ ...

  7. Android 六大存储

    Android平台进行存储的方式: 一.使用SharedPreferences存储 二.文件存储数据 三.SQLite数据库存储 四.使用ContentProvider存储数据 五.网络存储数据 今天 ...

  8. 【BZOJ4197】[Noi2015]寿司晚宴 状压DP+分解质因数

    [BZOJ4197][Noi2015]寿司晚宴 Description 为了庆祝 NOI 的成功开幕,主办方为大家准备了一场寿司晚宴.小 G 和小 W 作为参加 NOI 的选手,也被邀请参加了寿司晚宴 ...

  9. EasyNVR H5无插件摄像机直播解决方案前端解析之:引用videojs无法自动播放

    关于videojs自动播放问题 播放流媒体多使用videojs来进行播放,videojs,本身自带自动播放属性: 通过添加autoplay(),来完成视频播放的自动加载: player = video ...

  10. VS2013 自动添加头部注释 -C#开发

    在团队开发中,头部注释是必不可少的.但在开发每次新建一个类都要复制一个注释模块也很不爽,所以得想个办法让开发工具自动生成我们所需要的模板.....操作方法如下: 方法/步骤 1 找你的vs安装目录, ...