最近公司有個項目需要從Android平臺訪問WebService接口,實現向發佈的函數傳遞對象。在網上找瞭一些資料,發現使用ksoap2可以調用WebService傳遞對象。
需要引入ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar
//WebService的命名空間
static final String namespace = “http://impl.service.suncreate.com”;
//服務器發佈的url
static final String url = http://10.100.3.41/axis2/services/UploadService;
final String methodName = “upload”; // 函數名
final int sessionID = “111111”; //sessionID
//創建HttpTransportSE對象,通過HttpTransportSE類的構造方法可以指定WebService的url
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;
//指定WebService的命名空間和函數名
SoapObject soapObject = new SoapObject(namespace, methodName);
//設置調用方法參數的值
soapObject.addProperty(“sessionID”, 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字符串