下载KSOAP包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包

然后新建android项目:并把下载的KSOAP包放在android项目的lib目录下:右键->build path->configure build path--选择Libraries,如图:

Android调用webservice示例教程

以下分为七个步骤来调用WebService方法:

第一:实例化SoapObject 对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称。如:

View Code
//命名空间
private static final String serviceNameSpace="http://WebXml.com.cn/";
//调用方法(获得支持的城市)
private static final String getSupportCity="getSupportCity";

//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);

第二步:假设方法有参数的话,设置调用方法参数

request.addProperty("参数名称","参数值");

第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):

View Code
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut
=request;

第四步:注册Envelope,

(new MarshalBase64()).register(envelope);

第五步:构建传输对象,并指明WSDL文档URL:

View Code
//请求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug
=true;

第六步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):

View Code
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);

第七步:解析返回数据:

View Code
if(envelope.getResponse()!=null){
return parse(envelope.bodyIn.toString());
}

/**************
* 解析XML
*
@param str
*
@return
*/
private static List<String> parse(String str){
String temp;
List
<String> list=new ArrayList<String>();
if(str!=null && str.length()>0){
int start=str.indexOf("string");
int end=str.lastIndexOf(";");
temp
=str.substring(start, end-3);
String []test
=temp.split(";");

for(int i=0;i<test.length;i++){
if(i==0){
temp
=test[i].substring(7);
}
else{
temp
=test[i].substring(8);
}
int index=temp.indexOf(",");
list.add(temp.substring(
0, index));
}
}
return list;
}

这样就成功啦。那么现在我们就来测试下吧,这里有个地址提供webService天气预报的服务的,我这里只提供获取城市列表:

View Code

相关文章:

  • 2022-12-23
  • 2022-02-13
  • 2021-09-27
  • 2021-09-08
  • 2021-07-26
猜你喜欢
  • 2022-02-04
  • 2021-08-05
  • 2021-06-09
  • 2021-09-03
  • 2022-12-23
  • 2021-10-19
相关资源
相似解决方案