在 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;
}
}
namespace、methodName、參數結構。envelope.dotNet = true,且 SOAP_ACTION 通常為 namespace + methodName。KvmSerializable 並註冊:envelope.addMapping(namespace, "TypeName", MyClass.class)。| 問題 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException: org.ksoap2... | 未導入 jar 或未勾選 Export | Gradle 依賴或手動加入 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。