引用: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. 【BIEE】数据透视表格第一列添加序号

    现在有这么一个需求,需要在数据透视图的表格前面条件一列序号,作为行号,如下图: 那么实现这个如何实现呢? 只需要在BIEE分析编辑界面,新建一列,然后公式定义为:RCOUNT(RSUM(1)) ,保存 ...

  2. iphone手机分辨率--持久维护

    6.5英寸 —— 1242 x 2688 px —— Xs Max 6.1英寸 —— 828 x 1792 px —— XR 5.8英寸 —— 1125 x 2436 px —— X/Xs 5.5英寸 ...

  3. jQuery与ajax的应用(一)

    <body> <div id="resText"></div> <div id="reshtml"></d ...

  4. CocoaAsyncSocket 文档1:Socket简单介绍

    前言 CocoaAsyncSocket是 IOS下广泛应用的Socket三方库,网上相关样例数不胜数.这里我就不直接上代码,本文由B9班的真高兴发表于CSDN博客.另辟一条思路:翻译SocketAsy ...

  5. springboot 项目中控制台打印日志以及每天生成日志文件

    1.控制台打印sql语句 只要在application.properties 中加入<configuration  scan="true" scanPeriod=" ...

  6. session 购物车

    package session; import java.io.IOException;import java.util.ArrayList;import java.util.List; import ...

  7. Tsung 初步介绍安装

    tsung是erlang的一个开源的一个压力测试工具,可以测试包括HTTP, WebDAV, Mysql, PostgreSQL, LDAP, and XMPP/Jabber等服务器.针对 HTTP ...

  8. 深入Asyncio(七)异步上下文管理器

    Async Context Managers: async with 在某些场景下(如管理网络资源的连接建立.断开),用支持异步的上下文管理器是很方便的. 那么如何理解async with关键字? 先 ...

  9. 通信协议之sdp---sdp会话协议

    (1)sdp 描述格式 (2)sdp example (3) sdp (1)sdp 描述格式 m=video 1234 RTP/AVP 96a=rtpmap:96 H264a=framerate:15 ...

  10. 前端编程提高之旅(三)----浏览器兼容之IE6

    在爱奇艺实习期间,乐帝主要负责移动端活动页面的制作,因为移动浏览器是随着智能手机兴起的,这就决定了移动端不会重蹈浏览器兼容问题的覆辙.一開始就比較好的支持web标准,而纵观整个互联网行业,移动web开 ...