在 Servlet API 中有一個 ServletContextListener 接口求晶,它能夠監(jiān)聽 ServletContext 對象的生命周期,實際上就是監(jiān)聽 Web 應用的生命周期鸵隧。當Servlet 容器啟動或終止Web 應用時寄疏,會觸發(fā)ServletContextEvent 事件甘苍,該事件由ServletContextListener 來處理。在 ServletContextListener 接口中定義了處理ServletContextEvent 事件的兩個方法列肢。實際上ServeltContextListener是生成ServeltContext對象之后調用的.
如此就可以相當于一個服務,形成每隔一段時間去百度車聯(lián)網(wǎng)上抓取數(shù)據(jù)宾茂,然后存起來瓷马,我們自己的客戶端在訪問我們提供的接口,來一定程度上突破訪問天氣次數(shù)限制跨晴。
首先需要先定義一個TimerTask:
public class WeatherTask extends TimerTask{
//判斷是否在抓取信息
public static boolean isRunning = false;
String baseUrl="http://api.map.baidu.com/telematics/v3/weather?";
//抓取的城市信息
String[] strArray={"鄭州","北京","石家莊"};
public static HashMap <String,String>hm=new HashMap<String,String>();
public WeatherTask() {
super();
}
private ServletContext context = null;
public WeatherTask(ServletContext context) {
this.context = context;
}
@Override
public void run() {
// TODO Auto-generated method stub
if (!isRunning) {
isRunning=true;
for(int i=0;i<strArray.length;i++){
String rs=result(strArray[i]);
if(rs!=null){
hm.put(strArray[i], rs);
}
if(i==strArray.length-1){
isRunning=false;
}
}
}else{
isRunning=false;
}
}
public String result(String city){
HashMap<String,String>hmCity=new HashMap<String,String>();
hmCity.put("location", city);
hmCity.put("output", "json");
hmCity.put("ak", "IuRqX0hMiTPnMwGKweGYBb3OnC20YICE");
HttpRequest req = HttpRequest.get(baseUrl, hmCity, true).readTimeout(10000).connectTimeout(1000000)
.uncompress(true).trustAllCerts().trustAllHosts().ignoreCloseExceptions(true);
System.out.println(req);
if (req.code() == 200) {
return req.body();
} else{
return null;
}
}
}
其次欧聘,實現(xiàn)ServletContextListener
public class ContextListener extends HttpServlet implements
ServletContextListener {
private static final long serialVersionUID = 1L;
private java.util.Timer timer = null;
private WeatherTask myjob;
private JSONObject js;
public ContextListener() {
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
timer.cancel();
System.out.println("定時器銷毀");
event.getServletContext().log("定時器銷毀");
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
timer = new java.util.Timer(true);
event.getServletContext().log("定時器已啟動");
myjob = new WeatherTask(event.getServletContext());
timer.schedule(myjob, 0, 3000000);
event.getServletContext().log("已經(jīng)添加任務調度表");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String city = req.getParameter("city");
city = new String(city.getBytes("iso-8859-1"), "utf-8");
String outStr;
if(!myjob.isRunning){
outStr= myjob.hm.get(city);
}else{
outStr="正在抓取";
}
JSONObject js = new JSONObject();
js.put("outstr", outStr);
PrintWriter out = resp.getWriter();
out.print(outStr);
}
注意:該項目get請求用了com.github.kevinsawicki.http.HttpRequest以及com.alibaba.fastjson.JSONObject
需要另行導入:
測試接口:
public class Test {
public static void main(String[] args) {
String baseUrl="http://localhost:8080/Weather/weather";
HashMap<String,String>hm=new HashMap();
hm.put("city", "鄭州");
HttpRequest req = HttpRequest.get(baseUrl, hm, true).readTimeout(1000000).connectTimeout(1000000)
.uncompress(true).trustAllCerts().trustAllHosts().ignoreCloseExceptions(true);
System.out.println(req);
if (req.code() == 200) {
System.out.println("re:"+req.body());
} else {
System.out.println("ccc");
}
}
}
demo下載