Java通過webservice接口獲取天氣信息


通過SOAP請求的方式獲取天氣信息並解析返回的XML文件。

參考: http://www.webxml.com.cn/WebServices/WeatherWS.asmx

 

import java.io.InputStream;  
import java.io.OutputStream;  
import java.io.OutputStreamWriter;  
import java.net.URL;  
import java.net.URLConnection;  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import org.w3c.dom.Document;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
  
/** 
 * @ClassName WeatherUtils 
 * @Description TODO 天氣信息數據來源(http://www.webxml.com.cn/) 
 * 根據城市或地區名稱查詢獲得未來三天內天氣情況、現在的天氣實況、天氣和生活指數: 
 * 調用方法如下:輸入參數:theCityName = 城市中文名稱(國外城市可用英文)或城市<span class="wp_keywordlink" style="margin: 0px; padding: 0px; border: 0px; background-color: transparent;"><a target=_blank href="http://www.xuebuyuan.com/" title="代碼" target="_blank" style="text-decoration: none; color: rgb(1, 150, 227);">代碼</a></span>(不輸入默認為上海市),如:上海 或 58367,如有 
 * 城市名稱重復請使用城市代碼查詢(可通過 getSupportCity 或 getSupportDataSet 獲得);返回數據: 一個一維數組 String(22),共有 
 * 23個元素。String(0) 到 String(4):省份,城市,城市代碼,城市圖片名稱,最后更新時間。String(5) 到 String(11):當天的 氣溫, 
 * 概況,風向和風力,天氣趨勢開始圖片名稱(以下稱:圖標一),天氣趨勢結束圖片名稱(以下稱:圖標二),現在的天氣實況,天氣和生活 
 * 指數。String(12) 到String(16):第二天的 氣溫,概況,風向和風力,圖標一,圖標二。String(17) 到 String(21):第三天的 氣溫, 
 * 概況,風向和風力,圖標一,圖標二。String(22) 被查詢的城市或地區的介紹 
 * @author zyj jayzh1993@gmail.com 
 * @date 2013-10-14 
 */  
public class WeatherUtils {  
    /** 
     * 獲取SOAP的請求頭,並替換其中的標志符號為用戶輸入的城市 
     *  
     * @param city 
     *            用戶輸入的城市名稱 
     * @return 客戶將要發送給服務器的SOAP請求 
     */  
    private static String getSoapRequest(String city) {  
        StringBuilder sb = new StringBuilder();  
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"  
                    + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "  
                    + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "  
                    + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"  
                    + "<soap:Body>    <getWeather xmlns=\"http://WebXml.com.cn/\">"  
                    + "<theCityCode>" + city  
                    + "</theCityCode>    </getWeather>"  
                    + "</soap:Body></soap:Envelope>");  
        return sb.toString();  
    }  
  
    /** 
     * 用戶把SOAP請求發送給服務器端,並返回服務器點返回的輸入流 
     *  
     * @param city 
     *            用戶輸入的城市名稱 
     * @return 服務器端返回的輸入流,供客戶端讀取 
     * @throws Exception 
     */  
    private static InputStream getSoapInputStream(String city) throws Exception {  
        try {  
            String soap = getSoapRequest(city);  
            if (soap == null) {  
                return null;  
            }  
            URL url = new URL(  
                    "http://www.webxml.com.cn/WebServices/WeatherWS.asmx");  
            URLConnection conn = url.openConnection();  
            conn.setUseCaches(false);  
            conn.setDoInput(true);  
            conn.setDoOutput(true);  
  
            conn.setRequestProperty("Content-Length", Integer.toString(soap  
                    .length()));  
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");  
            conn.setRequestProperty("SOAPAction",  
                    "http://WebXml.com.cn/getWeather");  
  
            OutputStream os = conn.getOutputStream();  
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");  
            osw.write(soap);  
            osw.flush();  
            osw.close();  
  
            InputStream is = conn.getInputStream();  
            return is;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
  
    /** 
     * 對服務器端返回的XML進行解析 
     *  
     * @param city 
     *            用戶輸入的城市名稱 
     * @return 字符串 用#分割 
     */  
    public static String getWeather(String city) {  
        try {  
            Document doc;  
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
            dbf.setNamespaceAware(true);  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            InputStream is = getSoapInputStream(city);  
            doc = db.parse(is);  
            NodeList nl = doc.getElementsByTagName("string");  
            StringBuffer sb = new StringBuffer();  
            for (int count = 0; count < nl.getLength(); count++) {  
                Node n = nl.item(count);  
                if(n.getFirstChild().getNodeValue().equals("查詢結果為空!")) {  
                    sb = new StringBuffer("#") ;  
                    break ;  
                }  
                sb.append(n.getFirstChild().getNodeValue() + "#");  
            }  
            is.close();  
            return sb.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
    /** 
     * 測試 
     * @param args 
     * @throws Exception 
     */  
    public static void main(String[] args) throws Exception {  
        String weatherInfo = getWeather("廣州");  
        System.out.println(weatherInfo);  
    }  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM