Android与服务器端数据交互基于SOAP协议整合android+webservice

上一节中我们通过http协议,采用HttpClient向服务器端action请求数据。当然调用服务器端方法获取数据并不止这一种。WebService也可以为我们提供所需数据,那么什么是webService呢?,它是一种基于SAOP协议的远程调用标准,通过webservice可以将不同操作系统平台,不同语言,不同技术整合到一起。

我们在PC机器java客户端中,需要一些库,比如XFire,Axis2,CXF等等来支持访问WebService,但是这些库并不适合我们资源有限的android手机客户端,做过JAVA ME的人都知道有KSOAP这个第三方的类库,可以帮助我们获取服务器端webService调用,当然KSOAP已经提供了基于android版本的jar包了,那么我们就开始吧:首先下载KSOAP包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包然后新建android项目:并把下载的KSOAP包放在android项目的lib目录下:右键->build path->configure build path--选择Libraries,如图:

2011041910424662.jpg


以下分为七个步骤来调用WebService方法:
第一:实例化SoapObject 对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称。如:
  1. //命名空间
  2. private static final String serviceNameSpace="http://WebXml.com.cn/";
  3. //调用方法(获得支持的城市)   
  4. private static final String getSupportCity="getSupportCity";
  5. //实例化SoapObject对象
  6. SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);
复制代码
第二步:假设方法有参数的话,设置调用方法参数
request.addProperty("参数名称","参数值");
第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):
  1. //获得序列化的Envelope
  2. SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  3. envelope.bodyOut=request;
复制代码
第四步:注册Envelope,

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

第五步:构建传输对象,并指明WSDL文档URL:
  1. //请求URL
  2. private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  3. //Android传输对象
  4. AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
  5. transport.debug=true;
复制代码
第六步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
  1. transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
复制代码
第七步:解析返回数据:

  1. if(envelope.getResponse()!=null){
  2.                 return parse(envelope.bodyIn.toString());
  3.             }

  4. /**************
  5.      * 解析XML
  6.      * @param str
  7.      * @return
  8.      */
  9.     private static List<String> parse(String str){
  10.         String temp;
  11.         List<String> list=new ArrayList<String>();
  12.         if(str!=null && str.length()>0){
  13.             int start=str.indexOf("string");
  14.             int end=str.lastIndexOf(";");
  15.             temp=str.substring(start, end-3);
  16.             String []test=temp.split(";");
  17.             
  18.              for(int i=0;i<test.length;i++){
  19.                  if(i==0){
  20.                      temp=test[i].substring(7);
  21.                  }else{
  22.                      temp=test[i].substring(8);
  23.                  }
  24.                  int index=temp.indexOf(",");
  25.                  list.add(temp.substring(0, index));
  26.              }
  27.         }
  28.         return list;
  29.     }
复制代码
这样就成功啦。那么现在我们就来测试下吧,这里有个地址提供webService天气预报的服务的,我这里只提供获取城市列表:
  1. //命名空间
  2. private static final String serviceNameSpace="http://WebXml.com.cn/";
  3. //请求URL
  4. private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  5. //调用方法(获得支持的城市)
  6. private static final String getSupportCity="getSupportCity";
  7. //调用城市的方法(需要带参数)
  8. private static final String getWeatherbyCityName="getWeatherbyCityName";
  9. //调用省或者直辖市的方法(获得支持的省份或直辖市)
  10. private static final String getSupportProvince="getSupportProvince";
复制代码
然后你可以在浏览器中输入地址(WSDL):serviceURL,你会看到一些可供调用的方法:
2011041911122138.jpg

我们选择获取国内外主要城市或者省份的方法吧:getSupportProvice,然后调用,你会发现浏览器返回给我们的是xml文档:
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. - <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/">
  3.   <string>直辖市</string>
  4.   <string>特别行政区</string>
  5.   <string>黑龙江</string>
  6.   <string>吉林</string>
  7.   <string>辽宁</string>
  8.   <string>内蒙古</string>
  9.   <string>河北</string>
  10.   <string>河南</string>
  11.   <string>山东</string>
  12.   <string>山西</string>
  13.   <string>江苏</string>
  14.   <string>安徽</string>
  15.   <string>陕西</string>
  16.   <string>宁夏</string>
  17.   <string>甘肃</string>
  18.   <string>青海</string>
  19.   <string>湖北</string>
  20.   <string>湖南</string>
  21.   <string>浙江</string>
  22.   <string>江西</string>
  23.   <string>福建</string>
  24.   <string>贵州</string>
  25.   <string>四川</string>
  26.   <string>广东</string>
  27.   <string>广西</string>
  28.   <string>云南</string>
  29.   <string>海南</string>
  30.   <string>新疆</string>
  31.   <string>西藏</string>
  32.   <string>台湾</string>
  33.   <string>亚洲</string>
  34.   <string>欧洲</string>
  35.   <string>非洲</string>
  36.   <string>北美洲</string>
  37.   <string>南美洲</string>
  38.   <string>大洋洲</string>
  39.   </ArrayOfString>
复制代码
我们可以用 listview来显示:

那么下面我将给出全部代码:
  1. public class WebServiceHelper {
  2.    
  3.     //WSDL文档中的命名空间
  4.     private static final String targetNameSpace="http://WebXml.com.cn/";
  5.     //WSDL文档中的URL
  6.     private static final String WSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
  7.       
  8.     //需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)
  9.     private static final String getSupportProvince="getSupportProvince";
  10.     //需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)
  11.     private static final String getSupportCity="getSupportCity";
  12.     //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
  13.     private static final String getWeatherbyCityName="getWeatherbyCityName";
  14.     /********
  15.      * 获得州,国内外省份和城市信息
  16.      * @return
  17.      */
  18.     public  List<String> getProvince(){
  19.         List<String> provinces=new ArrayList<String>();
  20.         String str="";
  21.         SoapObject soapObject=new SoapObject(targetNameSpace,getSupportProvince);
  22.         //request.addProperty("参数", "参数值");调用的方法参数与参数值(根据具体需要可选可不选)
  23.         
  24.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  25.         envelope.dotNet=true;
  26.         envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
  27.         AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
  28.         //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
  29.         try {
  30.             
  31.             httpTranstation.call(targetNameSpace+getSupportProvince, envelope);
  32.             SoapObject result=(SoapObject)envelope.getResponse();
  33.             //下面对结果进行解析,结构类似json对象
  34.             //str=(String) result.getProperty(6).toString();
  35.             
  36.             int count=result.getPropertyCount();
  37.             for(int index=0;index<count;index++){
  38.                 provinces.add(result.getProperty(index).toString());
  39.             }
  40.             
  41.         } catch (IOException e) {
  42.             // TODO Auto-generated catch block
  43.             e.printStackTrace();
  44.         } catch (XmlPullParserException e) {
  45.             // TODO Auto-generated catch block
  46.             e.printStackTrace();
  47.         }
  48.         return provinces;
  49.     }
  50.    
  51.     /**********
  52.      * 根据省份或者直辖市获取天气预报所支持的城市集合
  53.      * @param province
  54.      * @return
  55.      */
  56.     public  List<String> getCitys(String province){
  57.         List<String> citys=new ArrayList<String>();
  58.         SoapObject soapObject=new SoapObject(targetNameSpace,getSupportCity);
  59.         soapObject.addProperty("byProvinceName", province);
  60.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  61.         envelope.dotNet=true;
  62.         envelope.setOutputSoapObject(soapObject);
  63.         
  64.         AndroidHttpTransport httpTransport=new AndroidHttpTransport(WSDL);
  65.         try {
  66.             httpTransport.call(targetNameSpace+getSupportCity, envelope);
  67.             SoapObject result=(SoapObject)envelope.getResponse();
  68.             int count=result.getPropertyCount();
  69.             for(int index=0;index<count;index++){
  70.                 citys.add(result.getProperty(index).toString());
  71.             }
  72.             
  73.         } catch (IOException e) {
  74.             // TODO Auto-generated catch block
  75.             e.printStackTrace();
  76.         } catch (XmlPullParserException e) {
  77.             // TODO Auto-generated catch block
  78.             e.printStackTrace();
  79.         }
  80.         return citys;
  81.     }
  82.    
  83.     /***************************
  84.      * 根据城市信息获取天气预报信息
  85.      * @param city
  86.      * @return
  87.      ***************************/
  88.     public  WeatherBean getWeatherByCity(String city){
  89.         
  90.         WeatherBean bean=new WeatherBean();

  91.         SoapObject soapObject=new SoapObject(targetNameSpace,getWeatherbyCityName);
  92.         soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)
  93.         
  94.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  95.         envelope.dotNet=true;
  96.         envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
  97.         
  98.         
  99.         AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
  100.         //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
  101.         try {
  102.             httpTranstation.call(targetNameSpace+getWeatherbyCityName, envelope);
  103.             SoapObject result=(SoapObject)envelope.getResponse();
  104.             //下面对结果进行解析,结构类似json对象
  105.             bean=parserWeather(result);
  106.             
  107.         } catch (IOException e) {
  108.             // TODO Auto-generated catch block
  109.             e.printStackTrace();
  110.         } catch (XmlPullParserException e) {
  111.             // TODO Auto-generated catch block
  112.             e.printStackTrace();
  113.         }
  114.         return bean;
  115.     }
  116.    
  117.     /**
  118.      * 解析返回的结果
  119.      * @param soapObject
  120.      */
  121.     protected   WeatherBean parserWeather(SoapObject soapObject){
  122.         WeatherBean bean=new WeatherBean();
  123.         
  124.         List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
  125.         
  126.         
  127.         Map<String,Object> map=new HashMap<String,Object>();
  128.         
  129.         //城市名
  130.         bean.setCityName(soapObject.getProperty(1).toString());
  131.         //城市简介
  132.         bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
  133.         //天气实况+建议
  134.         bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString());
  135.         
  136.         //其他数据
  137.         //日期,
  138.         String date=soapObject.getProperty(6).toString();
  139.         //---------------------------------------------------
  140.         String weatherToday="今天:" + date.split(" ")[0];  
  141.         weatherToday+="\n天气:"+ date.split(" ")[1];
  142.         weatherToday+="\n气温:"+soapObject.getProperty(5).toString();
  143.         weatherToday+="\n风力:"+soapObject.getProperty(7).toString();
  144.         weatherToday+="\n";
  145.         
  146.         List<Integer> icons=new ArrayList<Integer>();
  147.    
  148.         icons.add(parseIcon(soapObject.getProperty(8).toString()));      
  149.         icons.add(parseIcon(soapObject.getProperty(9).toString()));
  150.          
  151.         map.put("weatherDay", weatherToday);
  152.         map.put("icons",icons);
  153.         list.add(map);
  154.          //-------------------------------------------------
  155.         map=new HashMap<String,Object>();
  156.         date=soapObject.getProperty(13).toString();
  157.         String weatherTomorrow="明天:" + date.split(" ")[0];  
  158.         weatherTomorrow+="\n天气:"+ date.split(" ")[1];
  159.         weatherTomorrow+="\n气温:"+soapObject.getProperty(12).toString();
  160.         weatherTomorrow+="\n风力:"+soapObject.getProperty(14).toString();
  161.         weatherTomorrow+="\n";
  162.         
  163.         icons=new ArrayList<Integer>();
  164.          
  165.         icons.add(parseIcon(soapObject.getProperty(15).toString()));      
  166.         icons.add(parseIcon(soapObject.getProperty(16).toString()));
  167.         
  168.         map.put("weatherDay", weatherTomorrow);
  169.         map.put("icons",icons);
  170.         list.add(map);
  171.         //--------------------------------------------------------------
  172.         map=new HashMap<String,Object>();
  173.         
  174.         date=soapObject.getProperty(18).toString();
  175.         String weatherAfterTomorrow="后天:" + date.split(" ")[0];  
  176.         weatherAfterTomorrow+="\n天气:"+ date.split(" ")[1];
  177.         weatherAfterTomorrow+="\n气温:"+soapObject.getProperty(17).toString();
  178.         weatherAfterTomorrow+="\n风力:"+soapObject.getProperty(19).toString();
  179.         weatherAfterTomorrow+="\n";
  180.         
  181.         icons=new ArrayList<Integer>();
  182.         icons.add(parseIcon(soapObject.getProperty(20).toString()));      
  183.         icons.add(parseIcon(soapObject.getProperty(21).toString()));
  184.         
  185.         map.put("weatherDay", weatherAfterTomorrow);
  186.         map.put("icons",icons);
  187.         list.add(map);
  188.         //--------------------------------------------------------------
  189.         
  190.         bean.setList(list);
  191.         return bean;
  192.     }
  193.    
  194.      //解析图标字符串
  195.      private int parseIcon(String data){
  196.         // 0.gif,返回名称0,
  197.          int resID=32;
  198.          String result=data.substring(0, data.length()-4).trim();
  199.           // String []icon=data.split(".");
  200.           // String result=icon[0].trim();
  201.           //   Log.e("this is the icon", result.trim());
  202.          
  203.            if(!result.equals("nothing")){
  204.                resID=Integer.parseInt(result.trim());
  205.            }
  206.          return resID;
  207.          //return ("a_"+data).split(".")[0];
  208.      }
  209. }
复制代码
以及帮助类:

  1. public class WebServiceUtil {
  2.    
  3.     //命名空间
  4.     private static final String serviceNameSpace="http://WebXml.com.cn/";
  5.     //请求URL
  6.     private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  7.     //调用方法(获得支持的城市)
  8.     private static final String getSupportCity="getSupportCity";
  9.     //调用城市的方法(需要带参数)
  10.     private static final String getWeatherbyCityName="getWeatherbyCityName";
  11.     //调用省或者直辖市的方法(获得支持的省份或直辖市)
  12.     private static final String getSupportProvince="getSupportProvince";
  13.      
  14.     /*************
  15.      * @return城市列表
  16.      *************/
  17.     public static List<String> getCityList(){
  18.         //实例化SoapObject对象
  19.         SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);
  20.         //获得序列化的Envelope
  21.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  22.         envelope.bodyOut=request;
  23.         (new MarshalBase64()).register(envelope);
  24.         //Android传输对象
  25.         AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
  26.         transport.debug=true;
  27.         
  28.         //调用
  29.         try {
  30.             transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
  31.             if(envelope.getResponse()!=null){
  32.                 return parse(envelope.bodyIn.toString());
  33.             }
  34.             
  35.         } catch (IOException e) {
  36.             // TODO Auto-generated catch block
  37.             e.printStackTrace();
  38.         } catch (XmlPullParserException e) {
  39.             // TODO Auto-generated catch block
  40.             e.printStackTrace();
  41.         }
  42.         
  43.         
  44.         return null;
  45.     }
  46.    
  47.    
  48.     public static List<String> getProviceList(){
  49.         //实例化SoapObject对象
  50.         SoapObject request=new SoapObject(serviceNameSpace, getSupportProvince);
  51.         //获得序列化的Envelope
  52.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  53.         envelope.bodyOut=request;
  54.         (new MarshalBase64()).register(envelope);
  55.         //Android传输对象
  56.         AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
  57.         transport.debug=true;
  58.         
  59.         //调用
  60.         try {
  61.             transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
  62.             if(envelope.getResponse()!=null){
  63.                 return null;
  64.             }
  65.             
  66.         } catch (IOException e) {
  67.             // TODO Auto-generated catch block
  68.             e.printStackTrace();
  69.         } catch (XmlPullParserException e) {
  70.             // TODO Auto-generated catch block
  71.             e.printStackTrace();
  72.         }
  73.         
  74.         
  75.         return null;
  76.     }
  77.    
  78.     /*************
  79.      * @param cityName
  80.      * @return
  81.      *************/
  82.     public static String getWeather(String cityName){
  83.      
  84.         return "";
  85.     }
  86.    
  87.     /**************
  88.      * 解析XML
  89.      * @param str
  90.      * @return
  91.      */
  92.     private static List<String> parse(String str){
  93.         String temp;
  94.         List<String> list=new ArrayList<String>();
  95.         if(str!=null && str.length()>0){
  96.             int start=str.indexOf("string");
  97.             int end=str.lastIndexOf(";");
  98.             temp=str.substring(start, end-3);
  99.             String []test=temp.split(";");
  100.             
  101.              for(int i=0;i<test.length;i++){
  102.                  if(i==0){
  103.                      temp=test[i].substring(7);
  104.                  }else{
  105.                      temp=test[i].substring(8);
  106.                  }
  107.                  int index=temp.indexOf(",");
  108.                  list.add(temp.substring(0, index));
  109.              }
  110.         }
  111.         return list;
  112.     }
  113.    
  114.      /*********
  115.       * 获取天气
  116.       * @param soapObject
  117.       */
  118.      private void parseWeather(SoapObject soapObject){
  119.          //String date=soapObject.getProperty(6);
  120.      }
  121. }
复制代码
以上就是我所作的查询天气预报的全部核心代码了,读者可以根据注释以及本文章了解下具体实现,相信很快就搞明白了,运行结果如下:

46.jpg
114.jpg
到此结束
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值