如何通過php用curl調用接口?

ADVERTISEMENT

如何通過php用curl調用接口?

首先是客戶端執行方法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;
 }
 ?>
ADVERTISEMENT

客戶端調用方法,可以在此配置基本信息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'] = '[email protected]';
 //$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();
 ?>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持路飯。

ADVERTISEMENT

本文地址:
ADVERTISEMENT
ADVERTISEMENT