此篇我们开始调用接口,我们在插件类中新定义一个方法,起名为send_post,在方法中我们通过系统配置获取接口调用地址。
百度给的例子中使用了php的curl,更高级的使用方法可以学习php_curl初始化和执行方法
下面我们结合一下百度站长提供的代码。
/**
* 发送数据
* @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类重写了此方法。
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");
}
}
现在我们的插件基本能够运行了,但是在结构上还可以进一步优化!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!