這篇文章主要介紹了typecho外掛程式編寫教程(六):調用介面,這是系列文章的最後一篇,需要的朋友可以參考下
此篇我們開始調用介面,我們在外掛程式類中新定義一個方法,起名為send_post,在方法中我們通過系統配置擷取介面調用地址。
百度給的例子中使用了php的CURL,更進階的使用方法可以學習PHP_cURL初始化和執行方法
下面我們結合一下百度站長提供的代碼。
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/** * 發送資料 * @param $url 準備發送的url * @param $options 系統配置 */ public static function send_post($url, $options){ //擷取API $api = $options->plugin('BaiduSubmitTest')->api; //準備資料 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"); } |
由於我們還沒有建立日誌系統,所以我們將日誌先寫入檔案,先看效果吧!
傳回值:
複製代碼 代碼如下:
{"remain":48,"success":1}
Good!看來沒有什麼問題!不過為了保險起見,我還是用typecho內建的http類重寫了此方法。
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public static function send_post($url, $options){ //擷取API $api = $options->plugin('BaiduSubmitTest')->api; //準備資料 if( is_array($url) ){ $urls = $url; }else{ $urls = array($url); } //為了保證成功調用,老高先做了判斷 if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('對不起, 您的主機不支援 php-curl 擴充而且沒有開啟 allow_url_fopen 功能, 無法正常使用此功能')); } //發送請求 $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"); } } |
現在我們的外掛程式基本能夠運行了,但是在結構上還可以進一步最佳化!