萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 使用 ksoap2 調用 WebService (SOAP 協議) 完整教程

依賴配置

在 build.gradle 中添加:

implementation 'com.google.code.ksoap2-android:ksoap2-android:3.6.4'

或手動導入 ksoap2-android-assembly-*.jar 到 libs 目錄。

核心類說明

  • SoapObject:構建 SOAP 請求體(命名空間 + 方法名 + 參數)
  • SoapSerializationEnvelope:封裝 SOAP 信封,設置版本 (VER11/VER12)、編碼、輸出對象
  • HttpTransportSE:HTTP 傳輸層,發起調用

完整調用示例

public class SoapClient {
    private static final String NAMESPACE = "urn:AppBackgroundSpEngine";
    private static final String METHOD_NAME = "appSignRight";
    private static final String WSDL_URL = "https://xxx/services/AppBackgroundSpEngine?wsdl";
    private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME; // 部分服務需 SOAP_ACTION

    public static OrderRelationResult callService(OrderRelationInput input) {
        if (input == null) throw new IllegalArgumentException("Input cannot be null");

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("transId", input.getTransId());
        request.addProperty("mobile", input.getUserId());
        request.addProperty("imsi", input.getImsi());
        request.addProperty("appId", input.getAppId());
        request.addProperty("timeStamp", input.getTimeStamp());
        request.addProperty("clientType", input.getClientType());
        request.addProperty("sig", input.getSig());

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = false; // 非 .NET 服務設置 false
        envelope.setOutputSoapObject(request);

        HttpTransportSE transport = new HttpTransportSE(WSDL_URL, 10000); // 10s 超時
        transport.debug = true; // 開啟調試可打印請求/響應 XML

        try {
            transport.call(SOAP_ACTION, envelope);
            SoapObject response = (SoapObject) envelope.bodyIn;
            if (response != null) {
                OrderRelationResult result = new OrderRelationResult();
                result.setResultCode(Integer.parseInt(response.getPropertyAsString("resultCode")));
                result.setTransId(response.getPropertyAsString("transId"));
                result.setType(Integer.parseInt(response.getPropertyAsString("type")));
                return result;
            }
        } catch (IOException | XmlPullParserException e) {
            Log.e("SoapClient", "SOAP call failed", e);
        }
        return null;
    }
}

關鍵參數獲取技巧

  1. 使用 SoapUI 導入 WSDL,自動生成請求報文,查看 namespace、methodName、參數結構。
  2. 若服務為 .NET (asmx),需設置 envelope.dotNet = true,且 SOAP_ACTION 通常為 namespace + methodName。
  3. 複雜類型參數需實現 KvmSerializable 並註冊:envelope.addMapping(namespace, "TypeName", MyClass.class)。

常見問題與解決

問題原因解決
ClassNotFoundException: org.ksoap2...未導入 jar 或未勾選 ExportGradle 依賴或手動加入 libs 並勾選
NetworkOnMainThreadException主線程發起網絡請求使用子線程、AsyncTask、RxJava、协程
SocketTimeoutException服務端響應超時增加 HttpTransportSE 構造函數 timeout 參數
XmlPullParserException: Unexpected token響應非標準 SOAP 或編碼不匹配檢查 envelope.encoding,打印 transport.requestDump/responseDump 分析
返回 null 或解析失敗命名空間/方法名/參數名大小寫錯誤對照 WSDL/SoapUI 嚴格核對

現代替代方案

新項目建議使用 Retrofit + SimpleXmlConverter 或 OkHttp 手動構建 XML,代碼更簡潔、類型安全、支援協程/Flow,維護性遠優於 ksoap2。

copyright © 萬盛學電腦網 all rights reserved