Ksoap2 获取webservice返回值的getResponse() 出现的问题

时间:2021-12-02 03:02:13

今天写了一个判断记录重复的webservcie 返回布尔类型

 // 判断序列号在数据库是否重复
public static boolean isSerialNumExist(String serialNumber)
throws IOException, XmlPullParserException {
boolean isExist = false;
String methodName = "IsSerialNumberExist"; // 方法名
HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); //SERVICE_URL为 webservice的地址
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
SoapObject soap = new SoapObject(SERVICE_NS, methodName);
// 传入参数
soap.addProperty("serialNumber", serialNumber);
envelope.bodyOut = soap;
// 设置webservice的提供者为.net平台的
envelope.dotNet = true;
ht.call(SERVICE_NS + methodName, envelope);
// SoapObject in = (SoapObject) envelope.getResponse();
String response=envelope.getResponse().toString(); //值为: false
SoapObject in = (SoapObject) envelope.bodyIn;
// String bodyIn=in.toString();
// 值为:IsSerialNumberExistResponse{IsSerialNumberExistResult=false; }
if (in != null) {
isExist = Boolean.valueOf(in.getProperty(methodName + "Result")
.toString());
}
return isExist;
}

一、SoapSerializationEnvelope携带输出参数与返回值:
(1)其属性bodyIn为SoapObject类型 内容格式为 methodName+Response{ methodName+Result=值;... } (要是返回的是字符串数组:

methodName+Response{ methodName+Result=anyType{stirng=value1;string=value2;...} })

  获取指定属性的值:
       SoapObject in = (SoapObject) envelope.bodyIn;
     in.getProperty(methodName+Result).toString();

(2)而我通过 getResponse()获取的返回值直接就是false (要是返回值是字符串数数组 其格式为: anyType{ string=value1; stirng=value2;...} )不能转换成SoapObject类型,此时貌似getResponse()就是什么soapprimitive类型了; 数组的话可以转换;

所以在使用的时候要么try catch 要么直接用bodyIn 就不会出错的样子,如下:

SoapObject result=null;
try{
result = (SoapObject) soapEnvelope.getResponse(); }
catch (ClassCastException e) {
result = (SoapObject)soapEnvelope.bodyIn;
}

二、不过还一个问题是: 这两种获取返回值的方式会有所不同,具体体现为 result.getProperty(String name) 传入的参数差异

返回单个值:

 getResponse():
object response=envelope.getResponse(); bodyIn:
object in=in.getProperty(methodName + "Result");

返回字符串数组:

 getResponse:
if (soapIn != null)
{
int count = soapIn.getPropertyCount(); // 属性个数
for (int i = ; i < count; i++)
{
soapIn.getProperty(i).toString(); // do as you like
}
} bodyIn:
if (soapIn != null)
{
SoapArray soapArray=soapIn.getProperty(methodName+"Result"); // 差异
int count = soapArray.getPropertyCount(); // 属性个数
for (int i = ; i < count; i++)
{
soapArray.getProperty(i).toString()
}
}