欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

typecho插件編寫教程(六):調(diào)用接口

 更新時間:2015年05月28日 15:26:09   投稿:junjie  
這篇文章主要介紹了typecho插件編寫教程(六):調(diào)用接口,這是系列文章的最后一篇,需要的朋友可以參考下

此篇我們開始調(diào)用接口,我們在插件類中新定義一個方法,起名為send_post,在方法中我們通過系統(tǒng)配置獲取接口調(diào)用地址。

百度給的例子中使用了php的CURL,更高級的使用方法可以學(xué)習(xí)PHP_cURL初始化和執(zhí)行方法

下面我們結(jié)合一下百度站長提供的代碼。

/**
   * 發(fā)送數(shù)據(jù)
   * @param $url 準(zhǔn)備發(fā)送的url
   * @param $options 系統(tǒng)配置
   */
  public static function send_post($url, $options){
    //獲取API
    $api = $options->plugin('BaiduSubmitTest')->api;

    //準(zhǔn)備數(shù)據(jù)
    if( is_array($url) ){
      $urls = $url;
    }else{
      $urls = array($url);
    }

    $ch = curl_init();
    $options = array(
      CURLOPT_URL => $api,
      CURLOPT_POST => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POSTFIELDS => implode("\n", $urls),
      CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);

    //記錄日志
    file_put_contents('/tmp/send_log', date('H:i:s') . $result . "\n");
  }

由于我們還沒有建立日志系統(tǒng),所以我們將日志先寫入文件,先看效果吧!

返回值:

復(fù)制代碼 代碼如下:

{"remain":48,"success":1}

Good!看來沒有什么問題!不過為了保險起見,我還是用typecho自帶的http類重寫了此方法。

public static function send_post($url, $options){
    //獲取API
    $api = $options->plugin('BaiduSubmitTest')->api;

    //準(zhǔn)備數(shù)據(jù)
    if( is_array($url) ){
      $urls = $url;
    }else{
      $urls = array($url);
    }

    //為了保證成功調(diào)用,老高先做了判斷
    if (false == Typecho_Http_Client::get()) {
      throw new Typecho_Plugin_Exception(_t('對不起, 您的主機不支持 php-curl 擴展而且沒有打開 allow_url_fopen 功能, 無法正常使用此功能'));
    }

    //發(fā)送請求
    $http = Typecho_Http_Client::get();
    $http->setData(implode("\n", $urls));
    $http->setHeader('Content-Type','text/plain');
    $result = $http->send($api);

    //記錄日志
    file_put_contents('/tmp/send_log', date('H:i:s') . $result . "\n");
  }
}

現(xiàn)在我們的插件基本能夠運行了,但是在結(jié)構(gòu)上還可以進一步優(yōu)化!

相關(guān)文章

最新評論