在android中調用webservice

來源:互聯網
上載者:User
2011-06-29在android中調用webservice

部落格分類:

  • Android
GoogleAndroid網路通訊協定WebServiceSOAP

在手機ANDROID中調用WEBSERVICE介面,需要使用ksoap2的JAR包,KSOAP2 地址:http://code.google.com/p/ksoap2-android/

調用 WebService 分以下幾步:

1、指定 WebService 的命名空間和調用方法 ;

2、設定調用方法的參數值,如果沒有參數,可以省略,設定方法的參數值的代碼如下:
rpc.addProperty("abc", "test");
要注意的是,addProperty方法的第1個參數雖然表示調用方法的參數名,但該參數值並不一定與服務端的WebService類中的方法參數名一致,只要設定參數的順序一致即可。
3、產生調用Webservice方法的SOAP請求資訊。

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = false; //這裡如果設定為TRUE,那麼在伺服器端將擷取不到參數值(如:將這些資料插入到資料庫中的話)
envelope.setOutputSoapObject(rpc);
建立SoapSerializationEnvelope對象時需要通過SoapSerializationEnvelope類的構造方法設定SOAP協議的版本號碼。
該版本號碼需要根據服務端WebService的版本號碼設定。
在建立SoapSerializationEnvelope對象後,不要忘了設定SOAPSoapSerializationEnvelope類的bodyOut屬性,
該屬性的值就是在第一步建立的SoapObject對象。

4、建立HttpTransportsSE對象。
這裡不要使用 AndroidHttpTransport ht = new AndroidHttpTransport(URL); 這是一個要到期的類
private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
HttpTransportSE ht = new HttpTransportSE(URL);
ht.debug = true;
5、使用call方法調用WebService方法
private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";
ht.call(SOAP_ACTION, envelope);

6、獲得WebService方法的返回結果
有兩種方法:
1、使用getResponse方法獲得返回資料。
2、使用 bodyIn 及 getProperty。

7、 這時候執行會出錯,提示沒有許可權訪問網路
需要修改 AndroidManifest.xml 檔案,賦予相應許可權
簡單來說就是增加下面這行配置:<uses-permission android:name="android.permission.INTERNET"></uses-permission>

相關文章

聯繫我們

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