一種簡便的呼叫webservice的方式
阿新 • • 發佈:2019-02-18
JAVA部分:package com.dhcc.utils;/** * 通用介面 */import java.io.IOException;import java.util.Map;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.xmlpull.v1.XmlPullParserException;/** * 功能描述:解析webservice */public class WsApiUtil { private static final Logger LOG = LoggerFactory.getLogger(WsApiUtil.class); /** * * 接收伺服器返回的SoapObject資料 * @param serviceUrl * @param methodName * @param requestCode * @param requestXml * @return * @throws Exception */ public static String loadSoapObject(String nameSpace,String serviceUrl,String methodName ,String Code,String XML){ String retData = null ; // 建立soapObject物件 SoapObject soapObject = new SoapObject(nameSpace, methodName); // 設定引數 soapObject.addProperty("RequestCode", Code); soapObject.addProperty("RequestXML", XML); // 建立SoapSerializationEnvelope物件,並設定WebService版本號 SoapSerializationEnvelope serializationEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // 設定serializationEnvelope物件的badyOut屬性 serializationEnvelope.bodyOut = soapObject; // 建立HttpTransportSE物件,並且確定wsdl網路地址 HttpTransportSE httpTransportSE = new HttpTransportSE(serviceUrl);// try { // httpTransportSE呼叫Call方法 httpTransportSE.call(nameSpace + "/" + methodName, serializationEnvelope); // 獲取返回的結果物件 if (serializationEnvelope.getResponse() != null) { SoapObject result = (SoapObject) serializationEnvelope.bodyIn; Object obj = result.getProperty(methodName+ "Result"); //obj: <Response><ResultCode>0</ResultCode><ResultDesc></ResultDesc><ResultList><Patinfo><name>張三</name><sex>男</sex><age>20</age></Patinfo><Patinfo><name>李四</name><sex>女</sex><age>22</age></Patinfo></ResultList></Response> retData = obj.toString(); } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e2) { e2.printStackTrace(); }catch (Exception e3) { e3.printStackTrace(); } System.out.println("HIS推送返回結果:"+retData); return retData ; }}使用jar包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar