標籤:android style blog http io color ar os 使用
原創文章,轉載請註明出處:http://www.blog.csdn.net/tangcheng_ok 要在Android調用WebService,必須需要一些庫來支援,上面的例子中是,我們通過XFire來訪問WebService,但這些庫對於我們Android用戶端就不適合了。這裡介紹一個google code上的一個開源項目Ksoap2-android,Ksoap2-android提供了一個輕量而高效的SOAP庫訪問WebService。 下載ksoap2-android-assembly-2.6.0-jar-with-dependencies,並將其添加到Android項目中,在這個例子中只是傳遞一個簡單的字串而已,一般的使用WebService都會用到xml或者json來共用資料,只要根據具體的需求,將envelope.bodyIn的資料進行解析就可以了。WebService服務端搭建請參看《Android調用WebService之服務端實現(一)》,沒什麼好說的了,直接上代碼吧<span style="font-size:16px;">package org.winplus.aws; import java.io.IOException; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { private final static String TAG = "MainActivity"; // 命名空間 private static final String serviceNameSpace = "http://192.168.217.1:8080/WebServiceDemo"; private static final String example = "example"; // 請求URL private static final String serviceURL = "http://192.168.217.1:8080/WebServiceDemo/services/HelloWorld"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { Log.e(TAG, getRequestData()); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } } /** * * @return * @throws IOException * @throws XmlPullParserException */ private String getRequestData() throws IOException, XmlPullParserException { // 執行個體化SoapObject對象,指定webService的命名空間以及調用方法的名稱 SoapObject request = new SoapObject(serviceNameSpace, example); // example方法中有一個String的參數,這裡將“android client”傳遞到example中 request.addProperty("message", "android client"); // 獲得序列化的Envelope SoapSerializationEnvelope envelope; envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = request; // Android傳輸對象 HttpTransportSE transport = new HttpTransportSE(serviceURL); transport.debug = true; // 調用WebService transport.call(serviceNameSpace + example, envelope); if (envelope.getResponse() != null) { return envelope.bodyIn.toString(); } return null; } } </span> 功能代碼比較簡單,在中有一個調用WebService解析天氣預報的例子,感興趣的去看吧。源碼下載==》
Android調用WebService之用戶端實現(二)