国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

使用Yahoo Service實現天氣預報

2019-11-18 12:46:29
字體:
來源:轉載
供稿:網友

天氣預告是非常有用的服務,假如能在網站上集成天氣預告,能極大地方便用戶查詢。

尋遍了國內所有的氣象站點,沒找見提供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.            }
            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);
    }
}



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿拉善右旗| 张家口市| 无锡市| 深水埗区| 新源县| 长治市| 定陶县| 白银市| 胶州市| 荣昌县| 习水县| 若尔盖县| 泾阳县| 高陵县| 扎囊县| 徐闻县| 义乌市| 邢台县| 云梦县| 敦化市| 务川| 鹤壁市| 延庆县| 铅山县| 五指山市| 台前县| 鹿邑县| 商南县| 德安县| 珠海市| 乐都县| 东光县| 正镶白旗| 铜山县| 新绛县| 布尔津县| 颍上县| 博客| 东安县| 南城县| 陇川县|