Android利用Soap读取WebService并且解析XML的DataSet数据

来源:互联网 发布:vue.js 双向绑定 编辑:程序博客网 时间:2024/06/05 22:45

一、Soap的结构
这里写图片描述

 调用webService需要以下几个参数:命名空间、Soap Action、WSDL的URL、方法名。接下来以调用火车列车信息数据为例,webService地址为:webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx?op=getDetailInfoByTrainCode

二、调用WebService
一般来说,调用webService通常需要几个步骤,在调用之前,我们需要下载Soap的jar包,网上有很多,不再赘述。
1、参数设置:上面说到的几个参数都要先设置,这主要依赖于你要调用的web’Service的网址:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
// 命名空间
String nameSpace = “http://WebXml.com.cn/“;
// 调用的方法名称
String methodName = “getDetailInfoByTrainCode”;
// EndPoint
String endPoint = “http//webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx”;
// SOAP Action
String soapAction = “http//WebXml.com.cn/getDetailInfoByTrainCode”;

 2、指定命名空间与调用方法名

[java] view plaincopy在CODE上查看代码片派生到我的代码片
// 指定WebService的命名空间和调用的方法名
SoapObject rpc = new SoapObject(nameSpace, methodName);

     3、设置参数:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
// 设置需调用WebService接口需要传入的两个参数TrainCode、userId
rpc.addProperty(“TrainCode”, params[0]);
rpc.addProperty(“UserID”,”“);

    4、生成调用WebService方法的SOAP请求信息

[java] view plaincopy在CODE上查看代码片派生到我的代码片
// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.bodyOut = rpc;

   5、是否允许调用.Net的WebService

[java] view plaincopy在CODE上查看代码片派生到我的代码片
// 设置是否调用的是dotNet开发的WebService
envelope.dotNet = true;
// 等价于envelope.bodyOut = rpc;
envelope.setOutputSoapObject(rpc);

   6、创建Http对象

[java] view plaincopy在CODE上查看代码片派生到我的代码片
HttpTransportSE transport = new HttpTransportSE(endPoint);
7、调用WebService方法
[java] view plaincopy在CODE上查看代码片派生到我的代码片
try {
// 调用WebService
transport.call(soapAction, envelope);
} catch (Exception e) {
e.printStackTrace();
}

   8、返回SoapObject对象

[java] view plaincopy在CODE上查看代码片派生到我的代码片
SoapObject object=null;
// 获取返回的数据
if(envelope.bodyIn instanceof SoapFault){
String str=((SoapFault)envelope.bodyIn).faultstring;
System.out.println(“2”+str);

}
else{
object = (SoapObject) envelope.bodyIn;
}

   三、解析WebService中的DataSet数据       由于列车时刻表是DataSet数据,所以我们必须对返回的结果进行解析,在网上查找方法后,自己琢磨终于成功解析,方法如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
SoapObject soap1=(SoapObject)object.getProperty(“getDetailInfoByTrainCodeResult”);
SoapObject childs=(SoapObject)soap1.getProperty(1);
SoapObject soap2=(SoapObject)childs.getProperty(0);
///
for(int i=0;i

0 0
原创粉丝点击