溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在php中利用curl方法調用接口

發布時間:2021-03-09 16:53:45 來源:億速云 閱讀:265 作者:Leah 欄目:開發技術

這篇文章將為大家詳細講解有關怎么在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;
  }
  ?>

客戶端調用方法,可以在此配置基本信息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();
?>

關于怎么在php中利用curl方法調用接口就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女