天天看點

天氣預報實作小方案

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"  frame0"></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格式

繼續閱讀