typecho插件编写教程六:调用接口

此篇我们开始调用接口,我们在插件类中新定义一个方法,起名为send_post,在方法中我们通过系统配置获取接口调用地址。

百度给的例子中使用了PHP的CURL,更高级的使用方法可以学习

下面我们结合一下百度站长提供的代码。

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");

}

由于我们还没有建立日志系统,所以我们将日志先写入文件,先看效果吧!

返回值:

代码如下:
Good!看来没有什么问题!不过为了保险起见,我还是用typecho自带的http类重写了此方法

plugin('BaiduSubmitTest')->api;
//准备数据
if( is_array($url) ){
  $urls = $url;
}else{
  $urls = array($url);
}

//为了保证成功<a href="https://www.jb51.cc/tag/diaoyong/" target="_blank" class="keywords">调用</a>,老高先做了判断
if (false == Typecho_Http_Client::get()) {
  throw new Typecho_Plugin_Exception(_t('对不起,您的主机<a href="https://www.jb51.cc/tag/buzhichi/" target="_blank" class="keywords">不支持</a> <a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a>-curl 扩展而且没有打开 allow_url_fopen <a href="https://www.jb51.cc/tag/gongneng/" target="_blank" class="keywords">功能</a>,无法正常使用此<a href="https://www.jb51.cc/tag/gongneng/" target="_blank" class="keywords">功能</a>'));
}

//发送请求
$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");

}
}

现在我们的插件基本能够运行了,但是在结构上还可以进一步优化!

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...