电竞比分网-中国电竞赛事及体育赛事平台

分享

使用Yahoo Service實現(xiàn)天氣預報

 starsiday 2006-08-09
使用Yahoo Service實現(xiàn)天氣預報
作者:Xuefeng 文章來源:本站原創(chuàng) 點擊數(shù):2159 更新時間:2006-4-18
【字體:

如果您有任何疑問,請到開發(fā)論壇上提問。

天氣預報是非常有用的服務(wù),如果能在網(wǎng)站上集成天氣預報,能極大地方便用戶查詢。

尋遍了國內(nèi)所有的氣象站點,沒找見提供Web服務(wù)的,太小氣了,只能去國外找。NOAA(www.)提供一個Web服務(wù),但是死活連不上服務(wù)器,估計被屏蔽了,其他提供全球天氣預報的有www.和yahoo,

不過的服務(wù)太麻煩,還需要注冊,相比之下,yahoo的天氣服務(wù)既簡單又快速,只需一個http請求,然后解析返回的XML即可獲得天氣預報。

以北京為例,在weather.yahoo.com查找北京的城市代碼為CHXX0008,對應(yīng)的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來響應(yīng)SAX事件:

/**
 * For more information, please visit:
http://www.
 * 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);
    }
}

運行結(jié)果:

Weather: Partly Cloudy, low=7, high=16
Weather: Sunny, low=7, high=20

Yahoo會返回當天和第二天的Weather預報。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多