最近工作有用到web
services,而這兩天也比較有空,就弄了一個獲取天氣預報的Util。以前以為這有多難,因為數據來源是個困難。現在用web
services的技術,這個就不用管了。說共享也好,說偷也好,總之是達到目的了。網上找了幾個提供web
services的網站。發現下面這個是相當不錯的。
http://www.webxml.com.cn/Webservices/WeatherWebService.asmx
下面就用java把具體的代碼寫寫吧!
這里我采用比較簡單的get請求調用,畢竟這也沒什么秘密可言,就用最簡單的就可以了。
還有,這里很多捕獲異常的東西給我去掉了,自己加吧!
public final class WeatherUtil
{
private static String SERVICES_HOST = "www.webxml.com.cn";
private static String WEATHER_SERVICES_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/";
private static String SUPPORT_CITY_URL = WEATHER_SERVICES_URL
+ "getSupportCity?byProvinceName=ALL";
private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL
+ "getWeatherbyCityName?theCityName=";
private WeatherUtil(){}
public static InputStream getSoapInputStream(String url)
{
InputStream is = null;
URL U = new URL(url);
URLConnection conn = U.openConnection();
conn.setRequestProperty("Host", SERVICES_HOST);
conn.connect();
is = conn.getInputStream();
return is;
}
//取得支持的城市列表
public static ArrayList<String> getSupportCity()
{
ArrayList cityList = null;
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(SUPPORT_CITY_URL);
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
int len = nl.getLength();
cityList = new ArrayList<String>(len);
for (int i = 0; i < len; i++)
{
Node n = nl.item(i);
String city = n.getFirstChild().getNodeValue();
cityList.add(city);
}
is.close();
return cityList;
}
//取得城市的天氣
public static ArrayList<String> getWeather(String city)
{
ArrayList weatherList = null;
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
//這里他的編碼格式就是這樣,我試了幾個也沒辦法。。只好這樣混過去了
InputStream is = getSoapInputStream(WEATHER_QUERY_URL
+ new String(city.getBytes("UTF-8"), "GBK"));
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
int len = nl.getLength();
weatherList = new ArrayList<String>(len);
for (int i = 0; i < len; i++)
{
Node n = nl.item(i);
String weather = n.getFirstChild().getNodeValue();
weatherList.add(weather);
}
is.close();
return weatherList;
}
public static void main(String[] args) throws Exception
{
ArrayList<String> weatherList = WeatherUtil.getWeather("59287");
// ArrayList<String> weatherList = WeatherUtil.getSupportCity();
for (String weather : weatherList)
{
System.out.println(weather);
}
}
}
文章來源 mccxj
鼠中無大將的博客 , 文章地址 http://mccxj.javaeye.com/blog/144161