`

J2EE工具类:WeatherUtil.java

阅读更多
package com.worthtech.app.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * 天气查询. 推荐使用此 google service 查询<br/>
 */
public class WeatherUtil {

		/**
		 * 使用 google 查询天气<br/>
		 * 上海: http://www.google.com/ig/api?hl=zh_cn&weather=shanghai
		 * 
		 * @param city 城市拼音, 如 北京: beijing
		 */
		public static String getWeather(String city) {
			StringBuilder sb = new StringBuilder();
			try {
				String ur = "http://www.google.com/ig/api?hl=zh_cn&weather=";
				URL url = new URL(ur + city);
				InputStream in = url.openStream();

				String data = "";
				// 将流转换为 文本. 此一过程是为了解决乱码问题
				java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
				int i = -1;
				while ((i = in.read()) != -1){
					bos.write(i);
				}

				// 转换编码为 GB18030, 否则会乱码
				data = bos.toString().replace("<?xml version=\"1.0\"?>","<?xml version=\"1.0\" encoding=\"GB18030\"?>");
						
				// 将文本转换成流
				InputStream is = new ByteArrayInputStream(data.getBytes());

				// 读取流
				Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
				
				NodeList info = doc.getElementsByTagName("forecast_information").item(0).getChildNodes();
				sb.append(info.item(4).getAttributes().item(0).getNodeValue())// 日期
					.append("|")
					.append(city)
					.append("|");

				// 今天的天气, 最高气温 最低气温
				NodeList today = doc.getElementsByTagName("forecast_conditions").item(0).getChildNodes();
				sb.append(today.item(0).getAttributes().item(0).getNodeValue())//星期
					.append("|")
					.append(today.item(1).getAttributes().item(0).getNodeValue())//最低气温1
					.append("℃|")
					.append(today.item(2).getAttributes().item(0).getNodeValue())//最高气温2
					.append("℃|")
					.append(today.item(3).getAttributes().item(0).getNodeValue())//晴的图标
					.append("|")
					.append(today.item(4).getAttributes().item(0).getNodeValue())//晴4
					;

			} catch (Exception e) {
				sb.append("获取天气失败或不存在此城市");
			}
			return sb.toString();
		}

		public static void main(String[] args) {
			System.out.println("上海天气: " + WeatherUtil.getWeather("shanghai"));
			System.out.println("香港天气: " + WeatherUtil.getWeather("hongkong"));
			System.out.println("北京天气: " + WeatherUtil.getWeather("beijing"));
		}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics