Android调用Webservice
Google为Android平台开发Web Service客户端提供了ksoap2-android项目,在这个网址下载开发包http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.1.0/ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar
使用 kspoap2-android调用webserice操作的步骤如下:
1、创建HttpTransportSE传说对象 传入webservice服务器地址
- final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);
2、 创建SoapObject对象,创建该对象时需要传入所要调用Wb Service的命名空间、Web Service方法名;如果有参数要传给Web Service服务器,调用SoapObject对象的addProperty(String name,Object value)方法来设置参数,该方法的name参数指定参数名;value参数指定参数值
- SoapObject soapObject = new SoapObject(PACE, M_NAME);
- soapObject.addProperty("byProvinceName ", citys);
3、创建SoapSerializationEnelope对象,并传入SOAP协议的版本号;并设置对象的bodyOut属性
- final SoapSerializationEnvelope soapserial = new SoapSerializationEnvelope(
- SoapEnvelope.VER11);
- soapserial.bodyOut = soapObject;
- // 设置与.NET提供的Web service保持有良好的兼容性
- soapserial.dotNet = true;
6、调用HttpTransportSE对象的call()方法,其中call的第一个参数soapAction,第二个为SoapSerializationEvelope对象 调用远程Web Service;
- // 调用HttpTransportSE对象的call方法来调用 webserice
- httpSE.call(PACE + M_NAME, soapserial);
7、获取返回的信息,并解析
- // 获取服务器响应返回的SOAP消息
- SoapObject result = (SoapObject) soapserial.bodyIn;
- SoapObject detail = (SoapObject) result.getProperty("getSupportProvinceResult");
- //解析返回信息
- for (int i = 0; i < detail.getPropertyCount(); i++) {
- citys.add(detail.getProperty(i).toString());
- }
实例:通过天气预报 Web 服务 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx来获取联动城市