天天看點

微信開發紀實之曆史上的今天服務

微信開發紀實之曆史上的今天服務

說明:此篇文章是看了柳峰老師的文章(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;

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;

         }

   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;

public class TodayInHistoryServiceUtil {

         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;

         }

         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;

         }

         @SuppressWarnings("deprecation")

         publicstatic boolean isOutOfDate(){

                   intdate_now = new java.util.Date().getDate();

                   intdate_DB = getTodayFromDB().getDate();

                   returndate_now==date_DB?false:true;

         }

         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;

         }

         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;

         }

         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;

         }

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

         }

}