Android與伺服器端資料互動(基於SOAP協議整合android+webservice)

來源:互聯網
上載者:User

上一節中我們通過http協議,採用HttpClient向伺服器端action請求資料。當然調用伺服器端方法擷取資料並不止這一種。WebService也可以為我們提供所需資料,

那麼什麼是webService呢?,它是一種基於SAOP協議的遠程調用標準,通過webservice可以將不同作業系統平台,不同語言,不同技術整合到一起。

  我們在PC機器java用戶端中,需要一些庫,比如XFire,Axis2,CXF等等來支援訪問WebService,但是這些庫並不適合我們資源有限的android手機用戶端,做過JAVA ME的人都知道有KSOAP這個第三方的類庫,可以協助我們擷取伺服器端webService調用,當然KSOAP已經提供了基於android版本的jar包了,那麼我們就開始吧:

首先下載KSOAP包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包

然後建立android項目:並把下載的KSOAP包放在android項目的lib目錄下:右鍵->build path->configure build path--選擇Libraries,

以下分為七個步驟來調用WebService方法:

第一:執行個體化SoapObject 對象,指定webService的命名空間(從相關WSDL文檔中可以查看命名空間),以及調用方法名稱。如:

View Code
//命名空間
private static final String serviceNameSpace="http://WebXml.com.cn/";
//調用方法(獲得支援的城市)
private static final String getSupportCity="getSupportCity";

//執行個體化SoapObject對象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);

第二步:假設方法有參數的話,設定調用方法參數

request.addProperty("參數名稱","參數值");

第三步:設定SOAP請求資訊(參數部分為SOAP協議版本號碼,與你要調用的webService中版本號碼一致):

View Code
//獲得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;

第四步:註冊Envelope,

(new MarshalBase64()).register(envelope);

第五步:構建傳輸對象,並指明WSDL文檔URL:

View Code
//請求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android傳輸對象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;

第六步:調用WebService(其中參數為1:命名空間+方法名稱,2:Envelope對象):

View Code
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);

第七步:解析返回資料:

View Code
if(envelope.getResponse()!=null){

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.