日期:2014-05-17  浏览次数:20615 次

JSP页面显示天气,webservice或引用链接?
最近在做项目,遇到了个问题就是需要在页面上显示天气,并且不是显示一个天气,而是要显示全国多个城市的天气,最少是省会和直辖市,再有就是一些景点的天气,还有国外城市的天气,用列表显示样式如下图:

[img=http://my.csdn.net/my/album/detail/1236756][/img]
[img=http://my.csdn.net/my/album/detail/1236755][/img]
[img=http://my.csdn.net/my/album/detail/1236754][/img]

我自己思考了下,有两种思路:1.直接引用链接,如<iframe src="http://m.weather.com.cn/m/pn12/weather.htm " width="245" height="110" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" charset="GBK" ></iframe> 这个可以根据你的IP所在城市显示天气,但是我需要多个城市的天气,而且这个链接并不稳定,我测试过,有的地方显示的是北京的天气,但所在城市不是北京。
2.调用webservice,如http://www.google.com/ig/api?hl=zh_cn&weather=
http://www.google.com/ig/api?hl=zh_cn&weather=
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
但是调用得到的都是一个城市的天气,或许可以用循环的方式得到多个,还有就是我的项目用的是SSH框架,最好是能拿到list绑定到页面上去,再有就是如果我需要天气用繁体和英文显示怎么做,设置字符集?如果谁有英文的天气webservice,求分享下,谢谢!!!
下面是我弄得一个调用天气预报的webservice代码:

package com.itsum.supertour.util.filter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

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

*/
public class WeatherUtils {

/**
* 使用 google 查询天气<br/>
* 上海: http://www.google.com/ig/api?hl=zh_cn&weather=shanghai

* @param city 城市拼音, 如 北京: beijing
* @return wuhan : 2010-02-27 天气: 晴, 温度: 8 - 20℃, 湿度: 88%, 风向: 东南、风速:4 米/秒
*/
public static List<StringBuilder> getweather(String city) {
StringBuilder sbd = 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();

// 解决乱码问题
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i = -1;
while ((i = in.read()) != -1)
bos.write(i);

// 使用 utf-8 编码. 若不使用则默认会使用本地编码 GB18030, 则会有乱码
InputStream inp = new ByteArrayInputStream(bos.toString()
.getBytes("utf-8"));

// 读取流
Document doc = DocumentBuilderFactory
.newInstance().newDocumentBuilder().parse(inp);

// 城市:
sbd.append(city).append(" : ");

NodeList n1 = getNode(doc, "forecast_information", 0);
// 日期
sbd.append(getAttributeValue(n1, 4, 0) + " ");

NodeList n2 = getNode(doc, "current_conditions", 0);
//System.out.println("天气: " + getAttributeValue(n2, 0, 0));
//System.out.println(getAttributeValue(n2, 3, 0));
//System.out.println(getAttributeValue(n2, 5, 0));

// 天气
sbd.append("天气: " + getAttributeValue(n2, 0, 0) + ", ");

NodeList n3 = getNode(doc, "forecast_conditions", 0);
// 最低气温
sbd.append("温度: " + getAttributeValue(n3, 1, 0));
sbd.append(" - ");
// 最高气