天气预报实现小方案

 

 

1、  iframe他人的劳动成果

好处:

坏处:不是所有的服务提供商都支持iframe,自己无法修改样式

: QQ天气

<iframe src="http://weather.news.qq.com/inc/ss295.htm" style="WIDTH: 212px; HEIGHT: 204px" border=0 marginWidth=0 marginHeight=0   frameBorder=no width=160 scrolling=no height=60></iframe>

中国天气网http://www.weather.com.cn

<iframesrc="http://www.weather.com.cn/static/custom/custom.html" height="193" scrolling="no"  frameborder="0"></iframe>

 

2、  java实现方式

使用技术httpclient抓取页面方式实现,其实也挺简单,不过依懒性太强,如果他人网站做了修改,也必须做出相应修改..维护成本高

HttpClient httpClient = new HttpClient();

httpClient.getHostConfiguration().setProxy("代理主机",80); //因为我本地用的是代理

String hostUrl = "http://www.weather.com.cn/static/custom/custom.html";//抓取地址

GetMethod getMethod = new GetMethod(hostUrl);

// 使用系统提供的默认的恢复策略

getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  new DefaultHttpMethodRetryHandler());

       try {

        // 执行getMethod

        int statusCode = httpClient.executeMethod(getMethod);

        if (statusCode != HttpStatus.SC_OK) {

         System.err.println("Method failed: " + getMethod.getStatusLine());

        }

        InputStream resStream = getMethod.getResponseBodyAsStream(); //文件较大。所以建义用流方式

BufferedReader br = new BufferedReader(new InputStreamReader(resStream));

        StringBuffer resBuffer = new StringBuffer(); 

        String resTemp = ""

        while((resTemp = br.readLine()) != null){ 

        resBuffer.append(resTemp);

 

        } 

        br.close();

    String response = resBuffer.toString();  //抓取的远程文件已经组织成字符串

3、  ajax+java实现方式

jquery+dom4j

实现方式相对较灵活,推荐用这种方式实现。因为ajax有跨域限制问题所以用java类做了一个代理,帮助与远程服务器通信,再把返回信息交给ajax处理

Ajax.js

$.ajax({

         type: "POST",

         url: "dataresource.jsp?city="+$("#city").val(),

         //dataType:"xml",//此处有不解,需要返回的是xml格式,写上确出现错误

         success :function(result){

                    do something

                 },

         error :function(msg){alert("e")}

     })

 

dataresource.jsp //最好把这个功能写在单独的类

 

String city = request.getParameter("city");

URL url = null;

String urlStr =null;

if(city!=null)

    urlStr = "http://www.google.com/ig/api?hl=zh_cn&weather="+city;

else

    urlStr = "http://www.google.com/ig/api?hl=zh_cn&weather=beijing";

url = new URL(urlStr);

 

Properties prop = System.getProperties();

prop.put("http.proxyHost","代理主机");

prop.put("http.proxyPort","80");

 

InputStream in = url.openStream();

InputStreamReader isr =new InputStreamReader(in,"gbk");

 

SAXReader reader = new SAXReader();

Document doc = reader.read(isr);;

response.getWriter().write(doc.asXML());//返回的是xml格式

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值