Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 中呼叫 WebService 介面的實作方法

編輯:關於 Android 程式設計

要在 Android 中訪問 WebService 介面,通常需要引入第三方套件 ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar。有了這個工具,就能以 SOAP 協議與遠端服務溝通。

以下是呼叫的完整流程:

// WebService 的命名空間
static final String namespace = "https://impl.service.suncreate.com";
// 伺服器發布的 URL
static final String url = "https://10.100.3.41/axis2/services/UploadService";
final String methodName = "upload"; // 函式名
final String sessionID = "111111"; // sessionID

// 建立 HttpTransportSE 物件,透過構造方法指定 WebService 的 URL
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;

// 指定 WebService 的命名空間與函式名
SoapObject soapObject = new SoapObject(namespace, methodName);
// 設定呼叫方法的參數值
soapObject.addProperty("sessionID", sessionID);
soapObject.addProperty("data", cds); // cds 為需要傳遞的物件

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
envelope.bodyOut = transport;
envelope.setOutputSoapObject(soapObject);

// 使用 call 方法呼叫 WebService
transport.call(null, envelope);
SoapObject sb = (SoapObject) envelope.bodyIn;
String xmlMessage = sb.toString(); // 取得從伺服器端返回的 XML 字串

整體流程可以歸納為:建立傳輸物件、設定命名空間與函式名、加入參數、封裝成 SoapSerializationEnvelope,最後呼叫 transport.call 送出請求,並從 envelope.bodyIn 中解析伺服器回傳的結果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved