1. 程式人生 > 程式設計 >php模擬post提交請求呼叫介面示例解析

php模擬post提交請求呼叫介面示例解析

php模擬post提交請求,呼叫介面

/**
   * 模擬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']  = '[email protected]';
    $o = "";
    foreach ( $post_data as $k => $v ) 
    { 
      $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,-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,-1);

    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch,$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']  = '[email protected]';
    //$post_data = array();
    $res = $this->request_post($url,$post_data);    
    print_r($res);

  }

到此這篇關於php模擬post提交請求呼叫介面示例解析的文章就介紹到這了,更多相關php模擬post提交請求呼叫介面內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!