调用webservice的事例 package BigMeat.Nada.weather; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.List; 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 static String _url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName="; private static List<String> msg=new ArrayList<String>(); /** * @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对返回的XML进行解释 * @param cityName * @return */ public static List<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"); if ("查询结果为空!".equals(nl.item(0).getFirstChild().getNodeValue())) { return null; } for (int i = 0; i < nl.getLength(); i++) { Node n=nl.item(i); msg.add(n.getFirstChild().getNodeValue()); } is.close(); return msg; } catch (Exception e) { e.printStackTrace(); return null; } } /** * @param args */ public static void main(String[] args) { List<String>list=getWeatherByCityName("suzhou"); } } controller层调用情况!
package BigMeat.Nada.Controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import BigMeat.Nada.util.EncodingTool; import BigMeat.Nada.weather.Weather; @Controller public class WeatherController { private static List<String> list_weather; @RequestMapping(value="getWeather={city}",method = RequestMethod.GET) public @ResponseBody List<String> getWeather(@PathVariable String city) { Weather weather=new Weather(); list_weather=weather.getWeatherByCityName(EncodingTool.encodeStr(city)); if (list_weather==null) { list_weather=new ArrayList<String>(); list_weather.add("查询结果为空!请确认是否输入正确"); } return list_weather; } }
天气预报
最新推荐文章于 2024-07-15 09:55:08 发布