WeatherUtil.java
package Util;
import com.google.gson.Gson;
import dao.WeatherInfo;
public class WeatherUtil {
public static WeatherInfo getWeatherInfo(String cityId)
{
String url = "http://www.weather.com.cn/data/cityinfo/"+cityId+".html";
String json = JsonUtil.loadJSON(url);
json=json.substring(json.indexOf(":")+1,json.length()-1);
System.out.println(json);
Gson gson=new Gson();
WeatherInfo getresult=gson.fromJson(json, dao.WeatherInfo.class);
return getresult;
}
}
测试:查询天气后用飞信发送
package test;
import java.io.IOException;
import org.junit.Test;
import dao.WeatherInfo;
import Util.FetionSend;
import Util.WeatherUtil;
public class TestWeather {
@Test
public void test() {
String cityID="101120601";
WeatherInfo weather=WeatherUtil.getWeatherInfo(cityID);
FetionSend fetion = new FetionSend();
fetion.setUser("18253591716");
fetion.setPasswd("***********");
fetion.setSendTo("18253591716");
fetion.setMessage("城市:"+weather.getCity()+" 最低温度:"+weather.getTemp1()+
" 最高温度:"+weather.getTemp2()+" 天气状况:"+weather.getWeather()+" 发布时间:"+weather.getPtime());
System.out.println(fetion.getMessage());
try {
fetion.send();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
感悟:就那么简单,不需要太多的jar包,只需要一个解析JSON的
下载链接
gson-2.2.4.jar
相关源码