Android与服务器端数据交互

 
 

 上一节中我们通过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
2011-6-6 18:47 上传
下载附件 (85.18 KB)
  以下分为七个步骤来调用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);
复制代码
第二步:假设方法有参数的话,设置调用方法参数:

  1. request.addProperty("参数名称","参数值");
复制代码
 第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):

  1. //获得序列化的Envelope
  2. SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  3. envelope.bodyOut=request;
复制代码
第四步:注册Envelope:

  1. (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
2011-6-6 18:47 上传
下载附件 (122.31 KB)
  我们选择获取国内外主要城市或者省份的方法吧: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.         
  28.         AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
  29.         //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
  30.         try {
  31.             
  32.             httpTranstation.call(targetNameSpace+getSupportProvince, envelope);
  33.             SoapObject result=(SoapObject)envelope.getResponse();
  34.             //下面对结果进行解析,结构类似json对象
  35.             //str=(String) result.getProperty(6).toString();
  36.             
  37.             int count=result.getPropertyCount();
  38.             for(int index=0;index<count;index++){
  39.                 provinces.add(result.getProperty(index).toString());
  40.             }
  41.             
  42.         } catch (IOException e) {
  43.             // TODO Auto-generated catch block
  44.             e.printStackTrace();
  45.         } catch (XmlPullParserException e) {
  46.             // TODO Auto-generated catch block
  47.             e.printStackTrace();
  48.         }
  49.         return provinces;
  50.     }
  51.    
  52.     /**********
  53.      * 根据省份或者直辖市获取天气预报所支持的城市集合
  54.      * @param province
  55.      * @return
  56.      */
  57.     public  List<String> getCitys(String province){
  58.         List<String> citys=new ArrayList<String>();
  59.         SoapObject soapObject=new SoapObject(targetNameSpace,getSupportCity);
  60.         soapObject.addProperty("byProvinceName", province);
  61.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  62.         envelope.dotNet=true;
  63.         envelope.setOutputSoapObject(soapObject);
  64.         
  65.         AndroidHttpTransport httpTransport=new AndroidHttpTransport(WSDL);
  66.         try {
  67.             httpTransport.call(targetNameSpace+getSupportCity, envelope);
  68.             SoapObject result=(SoapObject)envelope.getResponse();
  69.             int count=result.getPropertyCount();
  70.             for(int index=0;index<count;index++){
  71.                 citys.add(result.getProperty(index).toString());
  72.             }
  73.             
  74.         } catch (IOException e) {
  75.             // TODO Auto-generated catch block
  76.             e.printStackTrace();
  77.         } catch (XmlPullParserException e) {
  78.             // TODO Auto-generated catch block
  79.             e.printStackTrace();
  80.         }
  81.         return citys;
  82.     }
  83.    
  84.     /***************************
  85.      * 根据城市信息获取天气预报信息
  86.      * @param city
  87.      * @return
  88.      ***************************/
  89.     public  WeatherBean getWeatherByCity(String city){
  90.         
  91.         WeatherBean bean=new WeatherBean();

  92.         SoapObject soapObject=new SoapObject(targetNameSpace,getWeatherbyCityName);
  93.         soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)
  94.         
  95.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  96.         envelope.dotNet=true;
  97.         envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
  98.         
  99.         
  100.         AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
  101.         //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
  102.         try {
  103.             httpTranstation.call(targetNameSpace+getWeatherbyCityName, envelope);
  104.             SoapObject result=(SoapObject)envelope.getResponse();
  105.             //下面对结果进行解析,结构类似json对象
  106.             bean=parserWeather(result);
  107.             
  108.         } catch (IOException e) {
  109.             // TODO Auto-generated catch block
  110.             e.printStackTrace();
  111.         } catch (XmlPullParserException e) {
  112.             // TODO Auto-generated catch block
  113.             e.printStackTrace();
  114.         }
  115.         return bean;
  116.     }
  117.    
  118.     /**
  119.      * 解析返回的结果
  120.      * @param soapObject
  121.      */
  122.     protected   WeatherBean parserWeather(SoapObject soapObject){
  123.         WeatherBean bean=new WeatherBean();
  124.         
  125.         List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();        
  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.         return null;
  44.     }   
  45.    
  46.     public static List<String> getProviceList(){
  47.         //实例化SoapObject对象
  48.         SoapObject request=new SoapObject(serviceNameSpace, getSupportProvince);
  49.         //获得序列化的Envelope
  50.         SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
  51.         envelope.bodyOut=request;
  52.         (new MarshalBase64()).register(envelope);
  53.         //Android传输对象
  54.         AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
  55.         transport.debug=true;
  56.         
  57.         //调用
  58.         try {
  59.             transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
  60.             if(envelope.getResponse()!=null){
  61.                 return null;
  62.             }            
  63.         } catch (IOException e) {
  64.             // TODO Auto-generated catch block
  65.             e.printStackTrace();
  66.         } catch (XmlPullParserException e) {
  67.             // TODO Auto-generated catch block
  68.             e.printStackTrace();
  69.         }      
  70.         return null;
  71.     }
  72.    
  73.     /*************
  74.      * @param cityName
  75.      * @return
  76.      *************/
  77.     public static String getWeather(String cityName){
  78.      
  79.         return "";
  80.     }
  81.    
  82.     /**************
  83.      * 解析XML
  84.      * @param str
  85.      * @return
  86.      */
  87.     private static List<String> parse(String str){
  88.         String temp;
  89.         List<String> list=new ArrayList<String>();
  90.         if(str!=null && str.length()>0){
  91.             int start=str.indexOf("string");
  92.             int end=str.lastIndexOf(";");
  93.             temp=str.substring(start, end-3);
  94.             String []test=temp.split(";");
  95.             
  96.              for(int i=0;i<test.length;i++){
  97.                  if(i==0){
  98.                      temp=test[i].substring(7);
  99.                  }else{
  100.                      temp=test[i].substring(8);
  101.                  }
  102.                  int index=temp.indexOf(",");
  103.                  list.add(temp.substring(0, index));
  104.              }
  105.         }
  106.         return list;
  107.     }
  108.    
  109.      /*********
  110.       * 获取天气
  111.       * @param soapObject
  112.       */
  113.      private void parseWeather(SoapObject soapObject){
  114.          //String date=soapObject.getProperty(6);
  115.      } 

 116.    }

  1. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值