JSP從WebService取天氣預(yù)報(bào)數(shù)據(jù),很精簡(jiǎn)的代碼[效果圖]。
JSP從WebService取天氣預(yù)報(bào)數(shù)據(jù)。
網(wǎng)上也有相關(guān)的代碼,不過(guò)比較繁瑣,我改進(jìn)了一下。很簡(jiǎn)單地實(shí)現(xiàn)了。
package com.xxx.web;
import java.io.*;
import java.net.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Weather { private Weather() { /** } /** 得到一個(gè)String對(duì)象,剩下的就很好處理了。 最終實(shí)現(xiàn)效果:
posted on 2009-04-03 16:43 找個(gè)美女做老婆 閱讀(1666) 評(píng)論(0) 編輯 收藏
private static String _url = "
}
* @param cityName
* @return
*/
private static InputStream getSoapInputStream(String cityName) {
try {
/*
* URL url = new URL(_url + cityName); HttpURLConnection hc =
* (HttpURLConnection) url.openConnection(); hc.connect();
* InputStream urlStream = hc.getInputStream(); return urlStream;
*/
return new URL(_url + cityName).openStream();
} catch (Exception ex) {
return null;
}
/**
* 用W3C DOM對(duì)返回的XML進(jìn)行解釋
* @param cityName
* @return
*/
public static String getWeatherByCityName(String cityName) {
try {
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(cityName);
if (is == null){
return null;
}
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
Node n = nl.item(0);
String weather = n.getFirstChild().getNodeValue();
is.close();
return weather;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
* @param args
*/
public static void main(String[] args) {
System.out.print(getWeatherByCityName("北京"));
}
}