在 Servlet API 中有一个 ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。实际上ServeltContextListener是生成ServeltContext对象之后调用的.
如此就可以相当于一个服务,形成每隔一段时间去百度车联网上抓取数据,然后存起来,我们自己的客户端在访问我们提供的接口,来一定程度上突破访问天气次数限制。
首先需要先定义一个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;
}
}
}
其次,实现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("已经添加任务调度表");
}
@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下载