java编写天气预报插件
首先在上篇文章中已介绍了天气预报的界面和功能,这次主要介绍这个所用到的关键知识。
1,对webservise的调用,注意在这个程序中并不是应用第三方库来调用webservice,而是采用直接解析xml文件的方式:
try {URL U = new URL(url);URLConnection conn = U.openConnection();//URLConnection是抽象类是,是应用程序与URL之间的通信conn.setRequestProperty("Host", SERVICES_HOST);conn.connect();//打开到此 URL 引用的资源的通信链接is = conn.getInputStream();} catch (MalformedURLException e) {e.printStackTrace();//返回从此打开的连接读取的输入流} catch (IOException e) {e.printStackTrace();} return is; List<String> weatherList = new ArrayList<String>(); Document doc;//Document 接口表示整个 HTML 或 XML 文档。从概念上讲,它是文档树的根,并提供对文档数据的基本访问。 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);//生成的解析器将提供对 XML 名称空间的支持,则为 true try {DocumentBuilder db = dbf.newDocumentBuilder();//使用当前配置的参数创建一个新的 DocumentBuilder 实例。 InputStream is = getSoapInputStream(WEATHER_QUERY_URL + cityCode);doc = db.parse(is);//将给定 InputStream 的内容解析为一个 XML 文档,并且返回一个新的 DOM Document 对象NodeList nl = doc.getElementsByTagName("string");String code=this.getName(); if("".equals(code)){ //从Cookkies中读取 Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("myWeather")){ code=cookies[i].getValue(); } } if("".equals(code)){//Cookie里也没有 code="57494";//设置默认武汉 } }else{//写入Cookie Cookie cookie=new Cookie("myWeather",name.trim()); cookie.setMaxAge(360000000);//设置Cookie的存在时间,该cookie在3600秒后失效 response.addCookie(cookie);