用maven定制一个车联网的天气预报解析项目
1:首先我们要根据之前的学习先创建一个maven项目
本实例以Gao这个项目来介绍,我们要做的功能是把车联网返回的内容解析并格式化后显示出来。车联网天气查询api地址http://developer.baidu.com/map/carapi-7.htm
在此我们需要一个开发者密钥即访问接口中的参数ak。我已经申请好,没有直接使用了,没有的童鞋可以去申请一个。
2:添加新的依赖
由于我们要解析接口默认返回的xml格式的数据,所以我们要用到一些解析xml的jar包,本例子中用到了dom4j和jaxen相关的jar包来解析xml所需添加的依赖如下
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk13</classifier>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>velocity</groupId>
<artifactId>velocity-dep</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
3:由于代码比较多,实体类就不展示了,下面看主体代码 项目主程序MyWeather
package com.test.xml;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.PropertyConfigurator;
import com.test.util.Constants;
import com.test.util.VelocityTemplate;
import com.test.xml.entity.CityWeatherResponse;
/**
* 主程序
* @author Administrator
*/
public class MyWeather {
public static void main(String[] args) throws Exception {
// 初始化 Log4J
PropertyConfigurator.configure(MyWeather.class.getClassLoader()
.getResource("log4j.properties"));//maven项目的src/main/resources下
BaiduRetriever baidu = new BaiduRetriever();
//随机选取一个城市来查询天气
String city = BaiduRetriever.citys.get(new Random().nextInt(953)).getName();
InputStream ins = baidu.retrieve(city);
new MyWeather().start(ins);
}
public void start(InputStream dataIn) throws Exception {
// 解析数据
CityWeatherResponse response = new WeatherParser().parseWether(dataIn);
//返回正确的状态码进行解析
if(Constants.ERROR_SUCCESS.equals(response.getError())
&&Constants.STATUS_SUCCESS.equals(response.getStatus())){
// 用Velocity格式化输出数据
Map<String, Object> templateParam = new HashMap<String, Object>();
templateParam.put("curdate", response.getDate());
templateParam.put("pm25", response.getResults().getPm25());
templateParam.put("currentCity", response.getResults().getCurrentCity());
templateParam.put("weatherList", response.getResults().getWeatherData());
templateParam.put("indexList", response.getResults().getIndexList());
VelocityTemplate.parseVMTemplateToFile("weather.vm", templateParam);
/* String text = VelocityTemplate.parseVMTemplate("weather.vm", templateParam);
System.out.print(text);*/
}else{
System.err.println("返回结果中有错误信息");
}
}
}
然后是访问车联网的封装类,此类中还初始化了中国所有的城市信息,以便主程序中每次随机选择一个城市进行查询
BaiduRetriever
package com.test.xml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
import com.test.util.BaseTest;
import com.test.util.Constants;
import com.test.util.FastJson;
import com.test.util.SomeUtil;
import com.test.xml.entity.City;
import com.test.xml.entity.Weather;
public class BaiduRetriever extends BaseTest{
private static Logger log = Logger.getLogger(BaiduRetriever.class);
public static List<City> citys = new ArrayList<City>();
static{
String path = BaiduRetriever.class.getResource("").getPath().substring(1)+"Citys.json";
FileInputStream in =null;
BufferedReader br = null;
StringBuffer sbuf = new StringBuffer();
try{
File jsonFile = new File(path);
in = new FileInputStream(jsonFile);
br = new BufferedReader(new InputStreamReader(in));
String temp =null;
while((temp=br.readLine())!=null){
sbuf.append(temp);
}
}catch (Exception e) {
e.printStackTrace();
System.err.println("异常...");
}finally{
try {
br.close();
in.close();
} catch (IOException e) {
System.err.println("输入、输出流关闭异常");
e.printStackTrace();
}
}
try{
citys = FastJson.jsonToList(sbuf.toString(), City.class);
}catch (Exception e) {
System.out.println("json转化异常");
}
}
public InputStream retrieve(String location) throws Exception {
log.info("Retrieving Weather Data");
Map<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put("ak", Constants.AK);
paramMap.put("location", location);
return readContentFro
mGet(null, SomeUtil.exChangeMapToParam(paramMap));
}
public static void main(String[] args) throws Exception {
System.out.println(Weather.class.getDeclaredFields().length);
/*System.out.println(citys.size());
for (City city:citys) {
System.out.println(city.toString());
}
BaiduRetriever baidu = new BaiduRetriever();
//随机选取一个城市来查询天气
baidu.retrieve((citys.get(new Random().nextInt(953))).getName());*/
}
}
返回消息解析类WeatherParser
package com.test.xml;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.test.xml.entity.CityWeatherResponse;
import com.test.xml.entity.Index;
import com.test.xml.entity.Results;
import com.test.xml.entity.Weather;
public class WeatherParser {
/**
* 天气信息解析类
*
* @param in
* @return
*/
public CityWeatherResponse parseWether(InputStream in) {
CityWeatherResponse weatherRes = new CityWeatherResponse();
Results results = new Results();
List<Weather> weatherList = new ArrayList<Weather>();
List<Index> indexList = new ArrayList<Index>();
SAXReader xmlReader = createXmlReader();
try {
Document doc = xmlReader.read(in);
weatherList = assembleWeather(doc);
indexList = assembleIndex(doc);
results = assembleResults(doc, indexList, weatherList);
weatherRes = assembleResponse(doc, results);
} catch (DocumentException e) {
e.printStackTrace();
}
return weatherRes;
}
/**
* 组合天气信息
* @param doc
* @return
*/
@SuppressWarnings("unchecked")
private List<Weather> assembleWeather(Document doc){
List<Weather> weatherList = new ArrayList<Weather>();
List<Node> weather = doc.selectNodes("//CityWeatherResponse/results/weather_data/*");
for(int i=0;i<weather.size();){
Weather temp = new Weather();
temp.setDate(weather.get(i++).getText());
temp.setDayPictureUrl(weather.get(i++).getText());
temp.setNightPictureUrl(weather.get(i++).getText());
temp.setWeather(weather.get(i++).getText());
temp.setWind(weather.get(i++).getText());
temp.setTemperature(weather.get(i++).getText());
weatherList.add(temp);
}
return CollectionUtils.isNotEmpty(weatherList)?weatherList:null;
}
/**
* 组合小贴士信息
* @param doc
* @return
*/
@SuppressWarnings("unchecked")
private List<Index> assembleIndex(Document doc){
List<Index> indexList = new ArrayList<Index>();
List<Node> index = doc.selectNodes("//CityWeatherResponse/results/index/*");
for(int i=0;i<index.size();){
Index temp = new Index();
temp.setTitle(index.get(i++).getText());
temp.setZs(index.get(i++).getText());
temp.setTipt(index.get(i++).getText());
temp.setDes(index.get(i++).getText());
indexList.add(temp);
}
return CollectionUtils.isNotEmpty(indexList)?indexList:null;
}
/**
* 组合Results
* @param doc
* @return
*/
@SuppressWarnings("unused" )
private Results assembleResults(Document doc,List<Index> indexList,List<Weather> weatherData){
Results results = new Results();
String curCity = doc.selectSingleNode("//CityWeatherResponse/results/currentCity").getText();
String pm25 = doc.selectSingleNode("//CityWeatherResponse/results/pm25").getText();
results.setCurrentCity(StringUtils.isNotEmpty(curCity)?curCity:"不存在");
results.setPm25(StringUtils.isNotEmpty(pm25)?pm25:"不存在");
results.setWeatherData(weatherData);
results.setIndexList(indexList);
return results;
}
/**
* 组合CityWeatherResponse
* @param doc
* @return
*/
@SuppressWarnings("unused" )
private CityWeatherResponse assembleResponse(Document doc,Results results){
CityWeatherResponse cityWeatherResponse = new CityWeatherResponse();
String error = doc.selectSingleNode("//CityWeatherResponse/error").getText();
String status = doc.selectSingleNode("//CityWeatherResponse/status").getText();
String rsDate = doc.selectSingleNode("//CityWeatherResponse/date").getText();
cityWeatherResponse.setError(StringUtils.isNotEmpty(error)?error:"不存在");
cityWeatherResponse.setStatus(StringUtils.isNotEmpty(status)?status:"不存在");
cityWeatherResponse.setDate(StringUtils.isNotEmpty(rsDate)?rsDate:"不存在");
cityWeatherResponse.setResults(results);
return cityWeatherResponse;
}
private SAXReader createXmlReader()
SAXReader xmlReader = new SAXReader();
return xmlReader;
}
}
接着是生成html的Velocity模板文件weather.vm
#**
@author Relieved
@version 1.0
*#
##============================================
#*
首先显示天气信息,然后显示各种小生活小贴士
*#
##List遍历显示天气信息
<!DOCTYPE html>
<html class=" "style="">
<head>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 天气预报 </title>
</head>
<body>
<div>今天是<span style="color:#8470FF;font-weight:bold;">${curdate}</span></div>
<div><span style="color:#8470FF;font-weight:bold;">${currentCity}:</span>实时天气情况如下:</div>
<div>pm25指数为:<span style="color:#8470FF;font-weight:bold;">${pm25}</span></div>
<table border="1">
#foreach($weather in ${weatherList})
<tr style="background-color:#8470FF;" align="center">
<td>${weather.date}</td>
<td>${weather.weather}</td>
<td>白天:<img src="${weather.dayPictureUrl}"/></td>
<td>晚上:<img src="${weather.nightPictureUrl}"/></td>
<td>${weather.temperature}</td>
<td>${weather.wind}</td>
</tr>
#end
<tr style="background-color:#32cd32;"><td colspan="6">爱心小贴士:</td></tr>
#foreach($index in ${indexList})
<tr style="background-color:#32cd32;">
<td align="center">${index.title}</td>
<td align="center">${index.zs}</td>
<td align="center">${index.tipt}</td>
<td colspan="3">${index.des}</td>
</tr>
#end
</table>
##============================================
</body>
</html>
4:最后是运行我们的项目
mvn install
mvn exec:java -Dexec.mainClass=com.test.xml.MyWeather.Main
最后打开生成的weather.html效果如下图
至此本项目的功能展示完毕,项目稍后会上传,欢迎交流
时间: 2024-10-12 10:44:13