天气预报是非常有用的服务,如果能在网站上集成天气预报,能极大地方便用户查询。
寻遍了国内所有的气象站点,没找见提供web服务的,太小气了,只能去国外找。noaa(www.weather.gov)提供一个web服务,但是死活连不上服务器,估计被屏蔽了,其他提供全球天气预报的有www.weather.com和yahoo,
不过weather.com的服务太麻烦,还需要注册,相比之下,yahoo的天气服务既简单又快速,只需一个http请求,然后解析返回的xml即可获得天气预报。
以北京为例,在weather.yahoo.com查找北京的城市代码为chxx0008,对应的url为:
http://xml.weather.yahoo.com/forecastrss?u=c&p=chxx0008
然后,通过sax解析返回的xml:
url url = new url("http://xml.weather.yahoo.com/forecastrss?u=c&p=chxx0008");
inputstream input = url.openstream();
saxparserfactory factory = saxparserfactory.newinstance();
factory.setnamespaceaware(false);
saxparser parser = factory.newsaxparser();
parser.parse(input, new yahoohandler());
自己定义一个yahoohandler来响应sax事件:
/**
* for more information, please visit: http://www.crackj2ee.com
* author: liao xuefeng
*/
public class yahoohandler extends defaulthandler {
public void startelement(string uri, string localname, string qname, attributes attributes)
throws saxexception {
if("yweather:condition".equals(qname)) {
string s_date = attributes.getvalue(3);
try {
date publish = new simpledateformat("eee, dd mmm yyyy hh:mm a z",
locale.us).parse(s_date);
//system.out.println("publish: " + publish.tostring());
}
catch (exception e) {
e.printstacktrace();
throw new saxexception("cannot parse date: " + s_date);
}
}
else if("yweather:forecast".equals(qname)) {
string s_date = attributes.getvalue(1);
date date = null;
try {
date = new simpledateformat("dd mmm yyyy", locale.us).parse(s_date);
}
catch (exception e) {
e.printstacktrace();
throw new saxexception("cannot parse date: " + s_date);
}
int low = integer.parseint(attributes.getvalue(2));
int high = integer.parseint(attributes.getvalue(3));
string text = attributes.getvalue(4);
int code = integer.parseint(attributes.getvalue(5));
system.out.println("weather: "+ text + ", low=" + low + ", high=" + high);
}
super.startelement(uri, localname, qname, attributes);
}
}
运行结果:
weather: partly cloudy, low=7, high=16
weather: sunny, low=7, high=20
闽公网安备 35060202000074号