学习闲暇之余,写了个获取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获取天气预报的信息

    运行效果: 主要功能: 1,jsp页面输入省份和城市 根据条件获取当地的天气信息 2,java代码 利用第三方的省份和城市的路径地址 本工程主要实现java获取天气预报的信息步骤1,创建工程weath ...

  2. java获取https网站证书,附带调用https:webservice接口

    一.java 获取https网站证书: 1.创建一个java工程,新建InstallCert类,将以下代码复制进去 package com; import java.io.BufferedReader ...

  3. java获取图片原始尺寸

    java获取图片原始尺寸 URL url = null; InputStream is = null; BufferedImage img = null; try { url = new URL(pi ...

  4. java学习第13天( java获取当前时间,有关大数据的运算及精确数字运算,Date类)

    一 java获取当前时间 学习一个函数,得到当前时间的准确值 System.currectTimeMillis(). 可以得到以毫秒为单位的当前时间.它主要用于计算程序运行时间,long start= ...

  5. Java获取Web服务器文件

    Java获取Web服务器文件 如果获取的是服务器上某个目录下的有关文件,就相对比较容易,可以设定死绝对目录,但是如果不能设定死绝对目录,也不确定web服务器的安装目录,可以考虑如下两种方式: 方法一: ...

  6. 【java 获取数据库信息】获取MySQL或其他数据库的详细信息

    1.首先是 通过数据库获取数据表的详细列信息 package com.sxd.mysqlInfo.test; import java.sql.Connection; import java.sql.D ...

  7. java获取获得Timestamp类型的当前系统时间。以及java.util.date 、java.sql.Date之间的转换

    java获取取得Timestamp类型的当前系统时间java获取取得Timestamp类型的当前系统时间 格式:2010-11-04 16:19:42 方法1: Timestamp d = new T ...

  8. spring java 获取webapp下文件路径

    spring java 获取webapp下文件路径 @RequestMapping("/act/worldcup_schedule_time/imgdownload") @Resp ...

  9. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

随机推荐

  1. AOE网与关键路径简介

    前面我们说过的拓扑排序主要是为解决一个工程能否顺序进行的问题,但有时我们还需要解决工程完成需要的最短时间问题.如果我们要对一个流程图获得最短时间,就必须要分析它们的拓扑关系,并且找到当中最关键的流程, ...

  2. GO1.6语言学习笔记3-工具篇(SublimeText 3+GoSublime组合)

    选择SublimeText作为开发工具的原因,最最主要的是它够轻巧,搭配GO开发才能有飞一般的感觉.当然作为开发工具之一,Sublime组合工具也提供足够强大的功能. 自动化提示代码 保存的时候自动格 ...

  3. Jenkins 使用学习笔记

    3.1    Jenkins安装    2 3.1.1    Jenkins下载    2 3.1.2    Jenkins 安装    2 3.1.3    Jenkins 目录结构    3 3. ...

  4. jQuery.ajax() 如何设置 Headers 中的 Accept 内容

    其实很简单,首先如果是常见类型,则请直接设置 dataType 属性 $.ajax({ dataType: "json", type: "get", succe ...

  5. js获取控件位置以及不同浏览器中的差别

    js获取控件位置(坐标位置)在不同浏览器中的差别. //获取坐标位置 function getpos(e) { var t=e.offsetTop; var l=e.offsetLeft; var h ...

  6. 【Android】6.3 ProgressDialog

    分类:C#.Android.VS2015: 创建日期:2016-02-08 一.简介 进度条对话框(ProgressDialog)常用于不能在短时间内快速完成的操作,显示进度条的目的是为了让用户明白程 ...

  7. Java NIO- Selector 使用示例

    Selector selector = Selector.open(); channel.configureBlocking(false); SelectionKey key = channel.re ...

  8. Loadrunner常用操作

    LoadRunner 参数化 为什么需要参数化? 大众理解:为了更加真实的模拟用户操作 底层原理: 1,应用服务,数据库会校验该值的唯一性(unique key) 2,为了避免数据库的查询缓存对性能测 ...

  9. 每日英语:China Overtakes U.S. in Number of Diabetes Cases

    China is now home to the world's largest diabetes population. The number of people who have diabetes ...

  10. hdoj1160 FatMouse's Speed 动态规划

    FatMouse's Speed Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...