webservice使用的一些總結

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   ar   os   使用   

什麼是WebService:

這個不用我在這裡廢話,網上的資料一搜一大把,如果你沒有接觸過這方面的知識,你可以先去網上查一下。這裡我只想說一下我印象比較深刻的幾點:

WebService是基於soap協議的。說實話這個知識剛開始我理解的並不是很到位。這也在很長的時間局限了我在代碼過程中的思維。我會在後面一個關於天氣預報的執行個體中進行詳細介紹的。總之,所有的webService請求、應答都是建立在soap協議的基礎上的,而soap傳輸資料的載體是xml。關於soap協議的介紹,在W3C上有很詳細的教程。

WSDL是WebService的描述語言,它定義了Web Service做什麼,怎麼做和查詢的資訊。在驗證一個WebService是否好用的時候,我們通常會選則在瀏覽器中輸入http://…….*?wsdl。如果顯示出一個xml檔案,我們就認為這是好用的,反之就是停用。在項目剛剛開始的時候,我也是這麼天真的認為的,因為教程上都是這麼示範的。但事實並非如此,就如同以下調用天氣預報的wsdl。如果你在瀏覽器中輸入http://fhs.6617.com/getweather.asmx?WSDL,它是不顯示的,但事實證明這個webservice服務時可以使用的(你可以通過http://fhs.6617.com/getweather.asmx?WSDL產生本地代理類)。這也一直是初學WebService者的一個誤區。之所以不能通過瀏覽器訪問,可能原因是服務發行者,或者伺服器做了一些限制,就如同互連網上很多伺服器,我們可以訪問卻ping不同一樣,服務者做了一些限制。(我的猜測)

怎樣使用WebService

是不是調用WebService時,必須要得到wsdl?必須要產生本地代理類?

在回答這個問題,之前,我想先介紹一下網上一些資源:有很多熱心的人,收集了很多常用的WebService,如:http://lqixv.javaeye.com/blog/308407。其中羅列的每一種服務,作者都提供了三種串連:Endpoint Disco WSDL 。其實這就是隱約的告訴我們調用webservice服務的三種途徑。

就如同我們的項目,用戶端在調用電信WebService上行發簡訊時,是通過 wsdl產生本地代理類方式實行的。而在接收狀態報表下行時,採用的是 Endpoint方式(用戶端不需要產生本地代理類,只需要知道Endpoint地址)。

所以wsdl很重要,但並不是必須的,前提你能通過api,規範文檔等擷取你需要的地址、命名空間的相關資訊。

如何調用wsdl產生本地代理類:

通過wsdl產生本地代理類,有很多方式,既可以通過wsdl2java命令手動產生,也可以通過eclipse的axis2外掛程式、xfire外掛程式等。但是通過項目的實踐,覺得盡量還是通過axis2的wsdl2java的命令產生,會省去很多麻煩。比如說,如果你擁有很多的wsdl檔案,他們又是相互聯絡的,這樣你通過eclipse的外掛程式產生時,會出現錯誤。因為它只能一下載入一個wsdl檔案。這個問題在項目初期,讓我吃了很多的苦頭。。。。。

Axis2是一個比較常用的WebService引擎,大家可以通過到http://ws.apache.org/axis2/下載,其中其中axis2-1.4.1-bin.zip檔案中包含了Axis2中所有的jar檔案,以及命令工具, axis2-1.4.1-war.zip檔案則用於將WebService發布到Web容器中,網上有很多axis2教程,在這裡不再多說。

天氣預報調用執行個體:

下面的一個執行個體是調用天氣預報的一個例子,沒有採用wsdl產生本地代理類的方式,採用的是通過http請求直接存取服務端點的方法:

步驟是:

1、利用soap向webservice endpoint進行請求,取回請求結果

2、通過dom4J解析返回的xml流,得到所要的資訊。

通過這個例子相信大家,會對”webserviice是基於soap協議”的這句話有更深刻的理解,另外在使用dom4J解析xml返迴流的過程中,遇到了些麻煩,需要額外引入jaxen-1.1.1.jar包,否則程式會報org/jaxen/JaxenException的錯誤。並且在XML包含命名空間時,定位元素,需要按照xpath文法來寫。

下面是類的原始碼:

import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.URL;import java.net.URLConnection;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 類作用調用webservice得到天氣預報服務 * @author qsw-Myonlystar 2010-1-13上午09:59:45 */public class Weather {    /**     * 擷取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>    <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"                        + "<theCityName>" + city                        + "</theCityName>    </getWeatherbyCityName>"                        + "</soap:Body></soap:Envelope>");        return sb.toString();    }    /**     * 使用者把SOAP請求發送給伺服器端,並返回伺服器點返回的輸入資料流     * @param city 使用者輸入的城市名稱     * @return 伺服器端返回的輸入資料流,供用戶端讀取     * @throws Exception     */    public 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/WeatherWebService.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/getWeatherbyCityName");            OutputStream os = conn.getOutputStream();            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");            osw.write(soap);            osw.flush();            osw.close();            InputStream is = conn.getInputStream();            //System.out.println(is.toString());            return is;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * 通過dom4j對伺服器端返回的XML進行解析     * @param city 使用者輸入的城市名稱     * @return 符串 用,分割     */    public static String getWeather(String city) {        Document document=null;        SAXReader reader = new SAXReader();        String s="";        Map map=new HashMap();        map.put("design", "http://WebXml.com.cn/");        reader.getDocumentFactory().setXPathNamespaceURIs(map);        try {            InputStream is = getSoapInputStream(city);//得到輸入資料流            document=reader.read(is);//將輸入資料流轉化為document            String t=document.asXML();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        List nodes = document.selectNodes("//design:string");        for (Iterator it = nodes.iterator(); it.hasNext();) {            Element elm = (Element) it.next();            String text=elm.getText();            //System.out.println("fsffs"+text);            s=s+elm.getText()+"\n";        }        return s;    }    /**     * 測試函數     * @param args     */    public static void main(String args[]){        Weather w=new Weather();        System.out.println(w.getWeather("泰安"));    }}

 

另外向大家推薦一個比較好的網站,http://www.webxml.com.cn/zh_cn/index.aspx。上面又很多好的webservice可以供我們調用。

   

webservice使用的一些總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.