J2EE工具类:WeatherUtil.java

155 篇文章 0 订阅
59 篇文章 0 订阅

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"));
		}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值