1. 程式人生 > >ksoap2呼叫webservice

ksoap2呼叫webservice

使用ksoap2呼叫遠端webservice,程式碼如下:

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

//...

String WSDL_URI = "http://ncp.szscgl.com:9000/Interface/sDataInfrace.asmx?WSDL";
String NAMESPACE = "http://tempuri.org/";//namespace

String methodName = "checkIn"; //要呼叫的方法名稱
String paramXml = "..."; //傳送的內容,例如一段xml

String soapAction = NAMESPACE + methodName;
SoapObject request = new SoapObject(NAMESPACE, methodName);
	        
request.addProperty("strXML", paramXml); //引數名稱是strXML
	      
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
envelope.bodyOut = request; //由於是傳送請求,所以是設定bodyOut
envelope.dotNet = true; //由於是.net開發的webservice,所以這裡要設定為true
try{
	  HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
	  httpTransportSE.call(soapAction, envelope);
	  SoapObject object = (SoapObject) envelope.bodyIn;
	  return  object.getProperty(0).toString(); //返回的結果
}catch(Exception e){
	  e.printStackTrace();
	  System.out.println(methodName + "報錯:"+ e.getMessage());     	
	  return null;
}

jar的引用:

相比axis,ksoap2更好用。