学习闲暇之余,写了个获取yahoo天气预报的java小程序,仅供娱乐。


首先我们需要获取您需要查询城市对应的代号,我们可以用HashMap来查询,代码如下:

publicstatic HashMap<String, String> cityCode =new HashMap<String, String>();

/* 初始化城市代号 */privatevoid initCitys() {    cityCode.put("北京", "0008");    cityCode.put("天津", "0133");    cityCode.put("武汉", "0138");    cityCode.put("杭州", "0044");    cityCode.put("合肥 ", "0448");    cityCode.put("上海 ", "0116");    cityCode.put("福州 ", "0031");    cityCode.put("重庆 ", "0017");    cityCode.put("南昌 ", "0097");    cityCode.put("香港 ", "0049");    cityCode.put("济南 ", "0064");    cityCode.put("澳门 ", "0512");    cityCode.put("郑州 ", "0165");    cityCode.put("呼和浩特 ", "0249");    cityCode.put("乌鲁木齐 ", "0135");    cityCode.put("长沙 ", "0013");    cityCode.put("银川 ", "0259");    cityCode.put("广州 ", "0037");    cityCode.put("拉萨 ", "0080");    cityCode.put("海口 ", "0502");    cityCode.put("南京 ", "0100");    cityCode.put("成都 ", "0016");    cityCode.put("石家庄 ", "0122");    cityCode.put("贵阳 ", "0039");    cityCode.put("太原 ", "0129");    cityCode.put("昆明 ", "0076");    cityCode.put("沈阳 ", "0119");    cityCode.put("西安 ", "0141");    cityCode.put("长春 ", "0010");    cityCode.put("兰州 ", "0079");    cityCode.put("西宁 ", "0236");}

  


接下来我们要创建链接,以获取天气预报的XML文档

private Document getWeatherXML(String cityCode) throws IOException {        URL url =new URL("http://weather.yahooapis.com/forecastrss?p=CHXX"+ cityCode +"&u=c");        URLConnection connection = url.openConnection();        Document Doc = stringToElement(connection.getInputStream());return Doc;    }

  


您也可以选择保存获取的天气XML文档

/* 保存获取的天气信息XML文档 */privatevoid saveXML(Document Doc, String Path) {        TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer transformer;try {            transformer = transFactory.newTransformer();            DOMSource domSource =new DOMSource(Doc);            File file =new File(Path);            FileOutputStream out =new FileOutputStream(file);            StreamResult xmlResult =new StreamResult(out);            transformer.transform(domSource, xmlResult);        } catch (Exception e) {            System.out.println("保存文件出错!");        }    }

  


本人获取的一份XML保存如下

<?xml version="1.0" encoding="UTF-8" ?> - <rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" version="2.0">- <channel><title>Yahoo! Weather - Wuhan, CH</title> <link>http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html</link> <description>Yahoo! Weather for Wuhan, CH</description> <language>en-us</language> <lastBuildDate>Sat, 27 Mar 2010 11:00 pm CST</lastBuildDate> <ttl>60</ttl> <yweather:location city="Wuhan" country="CH" region=""/> <yweather:units distance="km" pressure="mb" speed="km/h" temperature="C"/> <yweather:wind chill="15" direction="110" speed="6.44"/> <yweather:atmosphere humidity="67" pressure="1015.92" rising="0" visibility="9.99"/> <yweather:astronomy sunrise="6:19 am" sunset="6:38 pm"/> - <image><title>Yahoo! Weather</title> <width>142</width> <height>18</height> <link>http://weather.yahoo.com</link> <url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url> </image>- <item><title>Conditions for Wuhan, CH at 11:00 pm CST</title> <geo:lat>30.58</geo:lat> <geo:long>114.27</geo:long> <link>http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html</link> <pubDate>Sat, 27 Mar 2010 11:00 pm CST</pubDate> <yweather:condition code="33" date="Sat, 27 Mar 2010 11:00 pm CST" temp="15" text="Fair"/> - <description>- <!--[CDATA[ <img src="http://l.yimg.com/a/i/us/we/52/33.gif" mce_src="http://l.yimg.com/a/i/us/we/52/33.gif"/><br /><b>Current Conditions:</b><br />Fair, 15 C<BR /><BR /><b>Forecast:</b><BR />Sat - Partly Cloudy. High: 18 Low: 9<br />Sun - Partly Cloudy. High: 20 Low: 12<br /><br /><a href="http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html" mce_href="http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>(provided by <a href="http://www.weather.com" mce_href="http://www.weather.com" >The Weather Channel</a>)<br/>

  ]]--> </description><yweather:forecast code="29" date="27 Mar 2010" day="Sat" high="18" low="9" text="Partly Cloudy"/> <yweather:forecast code="30" date="28 Mar 2010" day="Sun" high="20" low="12" text="Partly Cloudy"/> <guid isPermaLink="false">CHXX0138_2010_03_27_23_00_CST</guid> </item></channel></rss>- <!--  api7.weather.sp1.yahoo.com uncompressed/chunked Sat Mar 27 08:43:16 PDT 2010 -->

  


好啦,下面就是解析XML了,您看一下XML文档,如果您了解的话很容易获取其中的信息

/* 获取天气信息 */public String getWeather(String city) {        String result =null;try {            Document doc = getWeatherXML(GetWeatherInfo.cityCode.get(city));            NodeList nodeList = doc.getElementsByTagName("channel");for (int i =0; i < nodeList.getLength(); i++) {                Node node = nodeList.item(i);                NodeList nodeList1 = node.getChildNodes();for (int j =0; j < nodeList1.getLength(); j++) {                    Node node1 = nodeList1.item(j);if (node1.getNodeName().equalsIgnoreCase("item")) {                        NodeList nodeList2 = node1.getChildNodes();for (int k =0; k < nodeList2.getLength(); k++) {                            Node node2 = nodeList2.item(k);if (node2.getNodeName().equalsIgnoreCase("yweather:forecast")) {                                NamedNodeMap nodeMap = node2.getAttributes();                                Node lowNode = nodeMap.getNamedItem("low");                                Node highNode = nodeMap.getNamedItem("high");                                Node codeNode = nodeMap.getNamedItem("code");                                String day ="今天";if (result ==null) {                                    result ="";                                } else {                                    day ="\n明天";                                }                                result = result+ day+""+ dictionaryStrings[Integer                                                .parseInt(codeNode                                                        .getNodeValue())]+"\t最低温度:"+ lowNode.getNodeValue()+"℃ \t最高温度:"+ highNode.getNodeValue()+"℃ ";                            }                        }                    }                }            }            saveXML(doc, "C:\\Users\\ygui\\Desktop\\Weather.xml");        } catch (Exception e) {            e.printStackTrace();        }return result;    }

  


整个程序的代码如下:

package stwolf.hustbaidu.java.learn.filelist;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import java.util.HashMap;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;class GetWeatherInfo {publicstatic HashMap<String, String> cityCode =new HashMap<String, String>();privatefinal String[] dictionaryStrings = { "龙卷风", "热带风暴", "飓风", "强雷阵雨","雷阵雨", "小雨加雪", "雨加冰雹", "雪加冰雹", "冰雨", "毛毛雨", "冻雨", "阵雨", "阵雨", "小雪","零星小雪", "高吹雪", "雪", "冰雹", "雨夹雪", "尘", "雾", "薄雾", "多烟的", "大风", "有风","寒冷", "阴天", "夜间阴天", "白天阴天", "夜间多云", "白天多云", "夜间清亮", "晴朗", "转晴","转晴", "雨夹冰雹", "热", "雷阵雨", "雷阵雨", "雷阵雨", "雷阵雨", "大雪", "阵雪", "大雪","多云", "雷", "阵雪", "雷雨" };public GetWeatherInfo() {        initCitys();    }/* 初始化城市代号 */privatevoid initCitys() {        cityCode.put("北京", "0008");        cityCode.put("天津", "0133");        cityCode.put("武汉", "0138");        cityCode.put("杭州", "0044");        cityCode.put("合肥 ", "0448");        cityCode.put("上海 ", "0116");        cityCode.put("福州 ", "0031");        cityCode.put("重庆 ", "0017");        cityCode.put("南昌 ", "0097");        cityCode.put("香港 ", "0049");        cityCode.put("济南 ", "0064");        cityCode.put("澳门 ", "0512");        cityCode.put("郑州 ", "0165");        cityCode.put("呼和浩特 ", "0249");        cityCode.put("乌鲁木齐 ", "0135");        cityCode.put("长沙 ", "0013");        cityCode.put("银川 ", "0259");        cityCode.put("广州 ", "0037");        cityCode.put("拉萨 ", "0080");        cityCode.put("海口 ", "0502");        cityCode.put("南京 ", "0100");        cityCode.put("成都 ", "0016");        cityCode.put("石家庄 ", "0122");        cityCode.put("贵阳 ", "0039");        cityCode.put("太原 ", "0129");        cityCode.put("昆明 ", "0076");        cityCode.put("沈阳 ", "0119");        cityCode.put("西安 ", "0141");        cityCode.put("长春 ", "0010");        cityCode.put("兰州 ", "0079");        cityCode.put("西宁 ", "0236");    }private Document getWeatherXML(String cityCode) throws IOException {        URL url =new URL("http://weather.yahooapis.com/forecastrss?p=CHXX"+ cityCode +"&u=c");        URLConnection connection = url.openConnection();        Document Doc = stringToElement(connection.getInputStream());return Doc;    }/* 保存获取的天气信息XML文档 */privatevoid saveXML(Document Doc, String Path) {        TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer transformer;try {            transformer = transFactory.newTransformer();            DOMSource domSource =new DOMSource(Doc);            File file =new File(Path);            FileOutputStream out =new FileOutputStream(file);            StreamResult xmlResult =new StreamResult(out);            transformer.transform(domSource, xmlResult);        } catch (Exception e) {            System.out.println("保存文件出错!");        }    }/* 获取天气信息 */public String getWeather(String city) {        String result =null;try {            Document doc = getWeatherXML(GetWeatherInfo.cityCode.get(city));            NodeList nodeList = doc.getElementsByTagName("channel");for (int i =0; i < nodeList.getLength(); i++) {                Node node = nodeList.item(i);                NodeList nodeList1 = node.getChildNodes();for (int j =0; j < nodeList1.getLength(); j++) {                    Node node1 = nodeList1.item(j);if (node1.getNodeName().equalsIgnoreCase("item")) {                        NodeList nodeList2 = node1.getChildNodes();for (int k =0; k < nodeList2.getLength(); k++) {                            Node node2 = nodeList2.item(k);if (node2.getNodeName().equalsIgnoreCase("yweather:forecast")) {                                NamedNodeMap nodeMap = node2.getAttributes();                                Node lowNode = nodeMap.getNamedItem("low");                                Node highNode = nodeMap.getNamedItem("high");                                Node codeNode = nodeMap.getNamedItem("code");                                String day ="今天";if (result ==null) {                                    result ="";                                } else {                                    day ="\n明天";                                }                                result = result+ day+""+ dictionaryStrings[Integer                                                .parseInt(codeNode                                                        .getNodeValue())]+"\t最低温度:"+ lowNode.getNodeValue()+"℃ \t最高温度:"+ highNode.getNodeValue()+"℃ ";                            }                        }                    }                }            }            saveXML(doc, "C:\\Users\\ygui\\Desktop\\Weather.xml");        } catch (Exception e) {            e.printStackTrace();        }return result;    }public Document stringToElement(InputStream input) {try {            DocumentBuilder db = DocumentBuilderFactory.newInstance()                    .newDocumentBuilder();            Document doc = db.parse(input);return doc;        } catch (Exception e) {returnnull;        }    }}publicclass Test {publicstaticvoid main(String arg[]) {        GetWeatherInfo info =new GetWeatherInfo();        String weather = info.getWeather("武汉");        System.out.println(weather);    }}

Java获取yahoo天气预报相关推荐

  1. java获取新浪天气预报代码

    package com.test.commons;/*** java获取新浪天气预报代码*/ import java.io.FileNotFoundException; import java.io. ...

  2. java调用第三方天气预报API接口

    java调用第三方天气预报API接口 package com.sensordata.controller; import com.common.json.JSONObject; import java ...

  3. 基于Java+Swing实现天气预报系统

    基于Java+Swing实现天气预报系统 一.系统介绍 二.功能展示 1.主面 2.IP定位城市 3.通过城市名称查询天气状态 4.查看各城区的天气 三.代码展示 四.其他系统 五.获取源码 一.系统 ...

  4. Java获取天气情况的方式

    说明 经过搜集和参考网上的相关资料,Java获取天气情况数据的通用步骤如下: 调用天气接口api: 解析返回的XML 或 JSON数据: 这里我并不去用代码实现一个Demo,而是记录一下思路,以后有需 ...

  5. Java 获取当前时间之后的第一个周几,java获取当前日期的下一个周几

    Java 获取当前时间之后的第一个周几,java获取当前日期的下一个周几 //获得入参的日期 Calendar cd = Calendar.getInstance(); cd.setTime(date ...

  6. Java获取照片的Exif信息,并解析GPS

    Java获取照片的Exif信息,并解析GPS 1. 效果图 2. 什么是Exif? 3. 源代码 参考 ❤️ 这篇博客将介绍什么EXIF,以及如何用Java语言读取Exif信息,并转换经纬度为位置信息 ...

  7. java 获取已有字体,java获取本机全部可用字体

    java获取本机所有可用字体 //just for fun,那个28个字母的函数满满都是恶心 import java.awt.GraphicsEnvironment ; class Tester { ...

  8. Java 查看文件绝对路径,JAVA获取文件绝对路径的方法

    本文实例讲述了JAVA获取文件绝对路径的方法.分享给大家供大家参考.具体实现方法如下: /** * 获取一个类的class文件所在的绝对路径. 这个类可以是JDK自身的类,也可以是用户自定义的类,或者 ...

  9. JAVA获取资源的方法

    类名.class=对象.getClass() 获得该类的Class对象 java获取当前工作路径System.getProperty("user.dir"); java获取类所在路 ...

最新文章

  1. TimerHandler的简单应用
  2. java中的mmap实现--转
  3. 【iHMI43 应用演示】之 modbus 协议(从机)通信演示
  4. python安卓开发实例_python服务器与android客户端socket通信实例
  5. 浅层学习与深层学习_深层副本与浅层副本-以及如何在Swift中使用它们
  6. OCR训练常见问题(1)
  7. 函数(定义、参数、return、变量、作用域、预解析)
  8. web安全day43:网络扫描和Nmap的使用
  9. 在 Mac 上如何放大或缩小?
  10. 《机器学习实战》代码实现学习一 使用K-近邻算法改进约会网站的配对效果(数据准备)...
  11. 使用VS code编辑md文件,并导出pdf
  12. Linux(1)之文件“776”
  13. 企业信息安全整体架构
  14. c++ 工厂模式简介和应用场景
  15. UltraEdit下Shift键失效
  16. 网络对抗技术 实验三
  17. Unity任意轴向朝向某目标实现LookAt功能
  18. JAVA中的protected的访问权限只有在本类同包类和子类吗?
  19. 深度置信网 DBNs
  20. 2021单机游戏排行榜前十名

热门文章

  1. 关于spring读取配置文件的两种方式
  2. Linux下快捷键使用
  3. 即使连网了ping也会失败
  4. 在不重装系统的情况下撤底删除oracle数据库及oralce的相关软件
  5. vector 结构体类型 使用 排序
  6. TopShell管理服务
  7. WPF 4 日历控件(Calendar)
  8. 【清北前紧急补课3】水题集锦
  9. 根据当前时间查询上月26号的日期 本月月25号的日期
  10. Android之使用HTTP协议的Get/Post方式向服务器提交数据