最近要用到web services,而这两天也比较有空,就弄了一个获取天气预报的Util。以前以为这有多难,因为数据来源是个困难。现在用web services的技术,发现下面这个是相当不错的。
下面就用java把具体的代码写写吧!
这里我采用比较简单的get请求调用,毕竟这也没什么秘密可言,就用最简单的就可以了。
还有,这里很多捕获异常的东西给我去掉了,自己加吧!
1 public final class WeatherUtil 2 { 3 private static String SERVICES_HOST = "www.webxml.com.cn"; 4 private static String WEATHER_SERVICES_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/"; 5 private static String SUPPORT_CITY_URL = WEATHER_SERVICES_URL 6 + "getSupportCity?byProvinceName=ALL"; 7 private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL 8 + "getWeatherbyCityName?theCityName="; 9 private WeatherUtil(){} 10 public static InputStream getSoapInputStream(String url) 11 { 12 InputStream is = null; 13 14 URL U = new URL(url); 15 URLConnection conn = U.openConnection(); 16 conn.setRequestProperty("Host", SERVICES_HOST); 17 conn.connect(); 18 is = conn.getInputStream(); 19 return is; 20 } 21 //取得支持的城市列表 22 public static ArrayList<String> getSupportCity() 23 { 24 ArrayList cityList = null; 25 Document doc; 26 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 27 dbf.setNamespaceAware(true); 28 DocumentBuilder db = dbf.newDocumentBuilder(); 29 InputStream is = getSoapInputStream(SUPPORT_CITY_URL); 30 doc = db.parse(is); 31 NodeList nl = doc.getElementsByTagName("string"); 32 int len = nl.getLength(); 33 cityList = new ArrayList<String>(len); 34 for (int i = 0; i < len; i++) 35 { 36 Node n = nl.item(i); 37 String city = n.getFirstChild().getNodeValue(); 38 cityList.add(city); 39 } 40 is.close(); 41 return cityList; 42 } 43 //取得城市的天气 44 public static ArrayList<String> getWeather(String city) 45 { 46 ArrayList weatherList = null; 47 Document doc; 48 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 49 dbf.setNamespaceAware(true); 50 DocumentBuilder db = dbf.newDocumentBuilder(); 51 //这里他的编码格式就是这样,我试了几个也没办法。。只好这样混过去了 52 InputStream is = getSoapInputStream(WEATHER_QUERY_URL 53 + new String(city.getBytes("UTF-8"), "GBK")); 54 doc = db.parse(is); 55 NodeList nl = doc.getElementsByTagName("string"); 56 int len = nl.getLength(); 57 weatherList = new ArrayList<String>(len); 58 for (int i = 0; i < len; i++) 59 { 60 Node n = nl.item(i); 61 String weather = n.getFirstChild().getNodeValue(); 62 weatherList.add(weather); 63 } 64 is.close(); 65 return weatherList; 66 } 67 68 public static void main(String[] args) throws Exception 69 { 70 ArrayList<String> weatherList = WeatherUtil.getWeather("59287"); 71 // ArrayList<String> weatherList = WeatherUtil.getSupportCity(); 72 for (String weather : weatherList) 73 { 74 System.out.println(weather); 75 } 76 } 77 }