天气预报

来源:互联网 发布:理财软件哪个好 编辑:程序博客网 时间:2024/06/05 15:08
调用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;@Controllerpublic 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;}}

 

0 0