微信开发纪实之历史上的今天服务
说明:此篇文章是看了柳峰老师的文章(http://blog.csdn.net/lyq8479/article/details/12785115)后自己动手写的。相比于柳峰老师的方法,我觉得我的方法有两项优点:
1. 主服务代码量更少(得益于HttpClient和Jsoup)
2. 实现了数据的平滑过渡
语言:java
代码:TodayInHistoryService.java
package com.wdyx.weixin.service;
import java.io.IOException;
importorg.apache.http.client.ClientProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* 历史上的今天 服务
*@author 帮杰
*
*/
public class TodayInHistoryService {
//数据源
publicstatic final String URL = "http://www.rijiben.com";
privateString todayInHistoryInfo = "";
publicTodayInHistoryService() throws ClientProtocolException, IOException{
StringBufferbuffer = new StringBuffer();
//得到网页源码
Stringhtml = HttpUtil.getHtml(URL);
//用Jsoup解析
Documentdoc = Jsoup.parse(html);
Elements elements =doc.select("div.listren").select("a");
for(Element element : elements){
buffer.append(element.text()).append("\n\n");
}
todayInHistoryInfo= buffer.substring(0, buffer.lastIndexOf("\n\n"));
}
publicString getTodayInHistoryInfo(){
returntodayInHistoryInfo;
}
/**
* 测试
*
* @param args
* @throws IOException
* @throws ClientProtocolException
*/
public static void main(String[] args) throws ClientProtocolException,IOException {
System.out.println(newTodayInHistoryService().getTodayInHistoryInfo());
}
}
测试结果:
1564年2月15日欧洲近代自然科学的创始人伽利略诞辰
1682年2月15日顾炎武逝世
1823年2月15日洋务运动倡导者李鸿章诞辰
1857年2月15日俄国音乐家格林卡逝世
1904年2月15日反清组织华兴会成立
1912年2月15日袁世凯任临时大总统
1935年2月15日东北抗日联军发表统一建制宣言
1937年2月15日国民党内外政策开始转变
1942年2月15日新加坡落入日军手中
1946年2月15日世界第一台电子计算机问世
1952年2月15日乔治六世下葬
1953年2月15日中央颁布《关于农业生产互助合作的决议》
1957年2月15日葛罗米柯就任外交部长
1961年2月15日美国18名滑冰运动员在空中丧生
1972年2月15日中国人民的朋友埃德加·斯诺逝世
1974年2月15日苏联驱逐作家索尔仁尼琴
1982年2月15日我国公布首批历史文化名城
1989年2月15日苏联军队全部撤出阿富汗
1990年2月15日美国等四国就联合反毒签署《卡塔赫纳声明》
为了不频繁调用服务通过网络抓取信息,我又写了一个用于数据的平滑过渡的类。
代码:TodayInHistoryServiceUtil.java
package com.wdyx.weixin.service;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import org.apache.http.client.ClientProtocolException;
import com.wdyx.weixin.util.MySQLUtil;
/**
* 这个是“历史上的今天”的工具类,主要用于数据的平滑过渡:
* 1、将当日抓取数据写入数据库
* 2、将当日数据从数据库中取出
*@author 帮杰
*
*/
public class TodayInHistoryServiceUtil {
/**
* 初始化数据库
* @return
* @throws SQLException
*/
publicstatic int initDB() throws SQLException{
intcount = -1;
Stringsql = "create table if not exists TodayInHistory("
+"today timestamp not null default current_timestamp,"
+"history varchar(1024) not null default '',"
+"primary key(today)) "
+"comment='todayInHistory' default character set utf8 collateutf8_bin";
Connectioncon = MySQLUtil.getConnection();
Statementsm = con.createStatement();
count= sm.executeUpdate(sql);
returncount;
}
/**
* 得到数据写入时间(以判断数据是否过期)
* @return 数据写入时间
*/
publicstatic Timestamp getTodayFromDB(){
Timestamptoday = null;
StringQuery = "SELECT today FROM TodayInHistory";
Connectioncon = MySQLUtil.getConnection();
Statementsm = null;
ResultSetrs = null;
try{
sm= con.createStatement();
rs= sm.executeQuery(Query);
if(rs.next()) {
today= rs.getTimestamp(1);
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
MySQLUtil.closeConnection(sm,rs, con);
}
returntoday;
}
/**
* 判断数据是否过期
* @return
*/
@SuppressWarnings("deprecation")
publicstatic boolean isOutOfDate(){
intdate_now = new java.util.Date().getDate();
intdate_DB = getTodayFromDB().getDate();
returndate_now==date_DB?false:true;
}
/**
* 从数据库取出“历史上的今天”数据
* @return “历史上的今天”数据
*/
publicstatic String getHistoryFromDB(){
Stringhistory = null;
StringQuery = "SELECT history FROM TodayInHistory";
Connectioncon = MySQLUtil.getConnection();
Statementsm = null;
ResultSetrs = null;
try{
sm= con.createStatement();
rs= sm.executeQuery(Query);
if(rs.next()) {
history= rs.getString(1);
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
MySQLUtil.closeConnection(sm,rs, con);
}
returnhistory;
}
/**
* 更新数据表
* @return 最新数据
* @throws IOException
* @throws ClientProtocolException
*/
publicstatic String updateDB() throws ClientProtocolException, IOException{
Stringhistory = new TodayInHistoryService().getTodayInHistoryInfo();
Connectioncon = MySQLUtil.getConnection();
Statementsm = null;
try{
sm= con.createStatement();
sm.addBatch("DELETEFROM TodayInHistory");
sm.addBatch("INSERTINTO TodayInHistory (today,history) VALUES (CURRENT_TIMESTAMP,'"+history+"')");
sm.executeBatch();
}catch (SQLException e) {
e.printStackTrace();
}finally {
MySQLUtil.closeConnection(sm,null,null);
}
returnhistory;
}
/**
* 删除数据表
* @return
*/
publicstatic boolean deleteDB(){
booleanflag = true;
Stringsql = "DROP TABLE TodayInHistory";
Connectioncon = MySQLUtil.getConnection();
Statementsm = null;
try{
sm= con.createStatement();
flag= sm.execute(sql);
}catch (SQLException e) {
flag= false;
e.printStackTrace();
}finally {
MySQLUtil.closeConnection(sm,null,null);
}
returnflag;
}
/**
* 流程控制
* @throws IOException
* @throws ClientProtocolException
* @throws SQLException
*/
publicstatic String getTodayInHistoryInfoFluently() throws ClientProtocolException,IOException {
Stringhistory = null;
//有两种情况需要更新表:1、表中无记录;2、表中有记录,但记录已过期
if(getHistoryFromDB()==null||isOutOfDate()){
history= updateDB();
}else{
history= getHistoryFromDB();
}
returnhistory;
}
//测试
publicstatic void main(String[] args) throws ClientProtocolException, IOException,SQLException{
/////////////System.out.println(deleteDB());/////////////
//如果表未就绪,初始化表
if(!MySQLUtil.hasTable("TodayInHistory")){
System.out.println("初始化数据表,状态:"+initDB());
}
System.out.println(getTodayInHistoryInfoFluently());
}
}