import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import net.sf.json.JSONObject;
/**
* 得到未来6天的天气(含今天)
* @author Chewl
*
*/
public class Weather {
String Ctiyid;
URLConnection connectionData;
StringBuilder sb;
BufferedReader br;// 读取data数据流
JSONObject jsonData;
JSONObject info;
static String zhuangkuang ;
public Weather(String Cityid) throws IOException ,NullPointerException{
// 解析本机ip地址
this.Ctiyid = Cityid;
// 连接中央气象台的API
URL url = new URL("http://m.weather.com.cn/data/" + Ctiyid + ".html");
connectionData = url.openConnection();
connectionData.setConnectTimeout(10000);
try {
br = new BufferedReader(new InputStreamReader(
connectionData.getInputStream(), "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
sb.append(line);
} catch (SocketTimeoutException e) {
Client.logger.error("加载天气预报时连接超时", e);
} catch (FileNotFoundException e) {
Client.logger.error("加载天气预报文件出错", e);
} catch (Exception e){
Client.logger.error("天气预报出现未知错误", e);
}
String datas = sb.toString();
jsonData = JSONObject.fromObject(datas);
info = jsonData.getJSONObject("weatherinfo");
//得到1到6天的天气情况
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for(int i=1;i<=1;i++){
//得到未来6天的日期
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, i-1);
Map<String,Object> map = new HashMap<String, Object>();
map.put("weather", info.getString("weather"+i).toString());//天气
map.put("temp", info.getString("temp"+i).toString());//温度
list.add(map);
}
//控制台打印出天气
for(int j=0;j<list.size();j++){
Map<String,Object> wMap = list.get(j);
zhuangkuang = (String) wMap.get("weather") + " " + (String) wMap.get("temp");
}
}
protected static String haveConfig(String cityname) {
Properties prop = new Properties();
InputStream in = null;
String citycode = null;
String bath= Weather.class.getResource("/").getPath();
try {
in = new FileInputStream(bath + "/city.properties");
prop.load(in);
citycode = prop.getProperty(cityname);
} catch (Exception e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
return citycode;
}
public static String search(String cityname){
try {
String citycode = haveConfig(cityname);
// new Weather("101210101"); // 101010100(北京)就是你的城市代码
new Weather(citycode); // 101010100(北京)就是你的城市代码
} catch (Exception e) {
e.printStackTrace();
}
return zhuangkuang ;
}
}
需要用到一个配置文件,里面包含各个天气的城市代码