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

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

 1 // 判断序列号在数据库是否重复
 2     public static boolean isSerialNumExist(String serialNumber)
 3             throws IOException, XmlPullParserException {
 4         boolean isExist = false;
 5         String methodName = "IsSerialNumberExist"; // 方法名
 6         HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); //SERVICE_URL为 webservice的地址
 7         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
 8                 SoapEnvelope.VER12);
 9         SoapObject soap = new SoapObject(SERVICE_NS, methodName);
10         // 传入参数
11         soap.addProperty("serialNumber", serialNumber);
12         envelope.bodyOut = soap;
13         // 设置webservice的提供者为.net平台的
14         envelope.dotNet = true;
15         ht.call(SERVICE_NS + methodName, envelope);
16         // SoapObject in = (SoapObject) envelope.getResponse();
17          String response=envelope.getResponse().toString(); //值为: false
18         SoapObject in = (SoapObject) envelope.bodyIn;
19         // String bodyIn=in.toString();
20         // 值为:IsSerialNumberExistResponse{IsSerialNumberExistResult=false; }
21         if (in != null) {
22             isExist = Boolean.valueOf(in.getProperty(methodName + "Result")
23                     .toString());
24         }
25         return isExist;
26     }

一、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) 传入的参数差异

返回单个值:

1 getResponse(): 
2 object response=envelope.getResponse();
3 
4 bodyIn:
5 object in=in.getProperty(methodName + "Result");

返回字符串数组:

 1 getResponse:
 3 if (soapIn != null) 
 4 {
 5     int count = soapIn.getPropertyCount(); // 属性个数
 6     for (int i = 0; i < count; i++) 
 7     {
 8  soapIn.getProperty(i).toString(); // do as you like
 9     }
10 }    
11 
12 bodyIn: 13 14 if (soapIn != null) 
15 {
16     SoapArray soapArray=soapIn.getProperty(methodName+"Result"); // 差异 17     int count = soapArray.getPropertyCount(); // 属性个数
18     for (int i = 0; i < count; i++) 
19     {
20  soapArray.getProperty(i).toString()
21     }
22 }    

 

 

 



                            

你可能感兴趣的:(webservice)