/**
* 传入选入的城市
*/
public String getWeather(String cityName, String fileAddr) {
// 获取google上的天气情况,写入文件
try {
URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather="
+ cityName);
InputStream inputstream = url.openStream();
String s, str;
BufferedReader in = new BufferedReader(new InputStreamReader(
inputstream));
StringBuffer stringbuffer = new StringBuffer();
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileAddr), "utf-8"));
while ((s = in.readLine()) != null) {
stringbuffer.append(s);
}
str = new String(stringbuffer);
out.write(str);
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取需要的数据
File file = new File(fileAddr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String str = "#";
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodelist1 = (NodeList) doc
.getElementsByTagName("forecast_conditions");
NodeList nodelist2 = nodelist1.item(0).getChildNodes();
String pic=nodelist2.item(3).getAttributes().item(0).getNodeValue();
pic=pic.substring(pic.lastIndexOf("/"));
System.out.println(pic);
str =pic
+ "#"
+ nodelist2.item(1).getAttributes().item(0).getNodeValue()
+ "℃-"
+ nodelist2.item(2).getAttributes().item(0).getNodeValue()
+ "℃";
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String args[]) {
WeatherReport ggw = new WeatherReport();
String cityName = "hefei";
String fileAddr = "F:\\weather\\" + cityName + ".xml";
String temperature = ggw.getWeather(cityName, fileAddr);
Date nowDate = new Date();
DateFormat dateformat = DateFormat.getDateInstance();
String today = dateformat.format(nowDate);
System.out.println(today + " " + cityName + "的天气情况是:" + temperature);
}
}
昨天从网上随便找一个webserver接口,写了半天,最后居然是要钱的!! 然后我又重新找了一免费的,在此共享一下,
这个是可以获得近三天的信息。根据你的需要获取啊!!
免费的哦!!