首页 > 其他分享 >Android web services详细使用

Android web services详细使用

时间:2023-07-28 19:06:06浏览次数:27  
标签:web getProperty String envelope toString services new Android soapObject


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,如图:

Android  web services详细使用_List

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

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




//        命名空间 
         
         
       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


//命名空间 private static final String serviceNameSpace="http://WebXml.com.cn/"; //请求URL private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx"; //调用方法(获得支持的城市) private static final String getSupportCity="getSupportCity"; //调用城市的方法(需要带参数) private static final String getWeatherbyCityName="getWeatherbyCityName"; //调用省或者直辖市的方法(获得支持的省份或直辖市) private static final String getSupportProvince="getSupportProvince";


 然后你可以在浏览器中输入地址(WSDL):serviceURL,你会看到一些可供调用的方法:

Android  web services详细使用_json_02

 我们选择获取国内外主要城市或者省份的方法吧:getSupportProvice,然后调用,你会发现浏览器返回给我们的是xml文档:


View Code

我们可以用 listview来显示:

那么下面我将给出全部代码:


View Code


public                 class         WebServiceHelper {         //        WSDL文档中的命名空间                          private 
         
       static 
         
       final 
        String targetNameSpace 
       = 
       " 
       http://WebXml.com.cn/ 
       " 
       ;  
       // 
       WSDL文档中的URL 
         
         
       private 
         
       static 
         
       final 
        String WSDL 
       = 
       " 
       http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 
       " 
       ;  
       // 
       需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息) 
         
         
       private 
         
       static 
         
       final 
        String getSupportProvince 
       = 
       " 
       getSupportProvince 
       " 
       ;  
       // 
       需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数) 
         
         
       private 
         
       static 
         
       final 
        String getSupportCity 
       = 
       " 
       getSupportCity 
       " 
       ;  
       // 
       根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数 
         
         
       private 
         
       static 
         
       final 
        String getWeatherbyCityName 
       = 
       " 
       getWeatherbyCityName 
       " 
       ;  
       /** 
       ****** * 获得州,国内外省份和城市信息 *  
       @return 
         
       */ 
         
       public 
        List 
       < 
       String 
       > 
        getProvince(){ List 
       < 
       String 
       > 
        provinces 
       = 
       new 
        ArrayList 
       < 
       String 
       > 
       (); String str 
       = 
       "" 
       ; SoapObject soapObject 
       = 
       new 
        SoapObject(targetNameSpace,getSupportProvince);  
       // 
       request.addProperty("参数", "参数值");调用的方法参数与参数值(根据具体需要可选可不选) 
         
        SoapSerializationEnvelope envelope 
       = 
       new 
        SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet 
       = 
       true 
       ; envelope.setOutputSoapObject(soapObject); 
       // 
       envelope.bodyOut=request; 
         
        AndroidHttpTransport httpTranstation 
       = 
       new 
        AndroidHttpTransport(WSDL);  
       // 
       或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL); 
         
         
       try 
        { httpTranstation.call(targetNameSpace 
       + 
       getSupportProvince, envelope); SoapObject result 
       = 
       (SoapObject)envelope.getResponse();  
       // 
       下面对结果进行解析,结构类似json对象  
       // 
       str=(String) result.getProperty(6).toString(); 
         
         
       int 
        count 
       = 
       result.getPropertyCount();  
       for 
       ( 
       int 
        index 
       = 
       0 
       ;index 
       < 
       count;index 
       ++ 
       ){ provinces.add(result.getProperty(index).toString()); } }  
       catch 
        (IOException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       catch 
        (XmlPullParserException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       return 
        provinces; }  
       /** 
       ******** * 根据省份或者直辖市获取天气预报所支持的城市集合 *  
       @param 
        province *  
       @return 
         
       */ 
         
       public 
        List 
       < 
       String 
       > 
        getCitys(String province){ List 
       < 
       String 
       > 
        citys 
       = 
       new 
        ArrayList 
       < 
       String 
       > 
       (); SoapObject soapObject 
       = 
       new 
        SoapObject(targetNameSpace,getSupportCity); soapObject.addProperty( 
       " 
       byProvinceName 
       " 
       , province); SoapSerializationEnvelope envelope 
       = 
       new 
        SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet 
       = 
       true 
       ; envelope.setOutputSoapObject(soapObject); AndroidHttpTransport httpTransport 
       = 
       new 
        AndroidHttpTransport(WSDL);  
       try 
        { httpTransport.call(targetNameSpace 
       + 
       getSupportCity, envelope); SoapObject result 
       = 
       (SoapObject)envelope.getResponse();  
       int 
        count 
       = 
       result.getPropertyCount();  
       for 
       ( 
       int 
        index 
       = 
       0 
       ;index 
       < 
       count;index 
       ++ 
       ){ citys.add(result.getProperty(index).toString()); } }  
       catch 
        (IOException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       catch 
        (XmlPullParserException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       return 
        citys; }  
       /** 
       ************************* * 根据城市信息获取天气预报信息 *  
       @param 
        city *  
       @return 
        ************************** 
       */ 
         
       public 
        WeatherBean getWeatherByCity(String city){ WeatherBean bean 
       = 
       new 
        WeatherBean(); SoapObject soapObject 
       = 
       new 
        SoapObject(targetNameSpace,getWeatherbyCityName); soapObject.addProperty( 
       " 
       theCityName 
       " 
       ,city); 
       // 
       调用的方法参数与参数值(根据具体需要可选可不选) 
         
        SoapSerializationEnvelope envelope 
       = 
       new 
        SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet 
       = 
       true 
       ; envelope.setOutputSoapObject(soapObject); 
       // 
       envelope.bodyOut=request; 
         
        AndroidHttpTransport httpTranstation 
       = 
       new 
        AndroidHttpTransport(WSDL);  
       // 
       或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL); 
         
         
       try 
        { httpTranstation.call(targetNameSpace 
       + 
       getWeatherbyCityName, envelope); SoapObject result 
       = 
       (SoapObject)envelope.getResponse();  
       // 
       下面对结果进行解析,结构类似json对象 
         
        bean 
       = 
       parserWeather(result); }  
       catch 
        (IOException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       catch 
        (XmlPullParserException e) {  
       // 
        TODO Auto-generated catch block 
         
        e.printStackTrace(); }  
       return 
        bean; }  
       /** 
        * 解析返回的结果 *  
       @param 
        soapObject  
       */ 
         
       protected 
        WeatherBean parserWeather(SoapObject soapObject){ WeatherBean bean 
       = 
       new 
        WeatherBean(); List 
       < 
       Map 
       < 
       String,Object 
       >> 
        list 
       = 
       new 
        ArrayList 
       < 
       Map 
       < 
       String,Object 
       >> 
       (); Map 
       < 
       String,Object 
       > 
        map 
       = 
       new 
        HashMap 
       < 
       String,Object 
       > 
       ();  
       // 
       城市名 
         
        bean.setCityName(soapObject.getProperty( 
       1 
       ).toString());  
       // 
       城市简介 
         
        bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount() 
       - 
       1 
       ).toString());  
       // 
       天气实况+建议 
         
        bean.setLiveWeather(soapObject.getProperty( 
       10 
       ).toString() 
       + 
       " 
       \n 
       " 
       + 
       soapObject.getProperty( 
       11 
       ).toString());  
       // 
       其他数据  
       // 
       日期, 
         
        String date 
       = 
       soapObject.getProperty( 
       6 
       ).toString();  
       // 
       --------------------------------------------------- 
         
        String weatherToday 
       = 
       " 
       今天: 
       " 
         
       + 
        date.split( 
       " 
         
       " 
       )[ 
       0 
       ]; weatherToday 
       += 
       " 
       \n天气: 
       " 
       + 
        date.split( 
       " 
         
       " 
       )[ 
       1 
       ]; weatherToday 
       += 
       " 
       \n气温: 
       " 
       + 
       soapObject.getProperty( 
       5 
       ).toString(); weatherToday 
       += 
       " 
       \n风力: 
       " 
       + 
       soapObject.getProperty( 
       7 
       ).toString(); weatherToday 
       += 
       " 
       \n 
       " 
       ; List 
       < 
       Integer 
       > 
        icons 
       = 
       new 
        ArrayList 
       < 
       Integer 
       > 
       (); icons.add(parseIcon(soapObject.getProperty( 
       8 
       ).toString())); icons.add(parseIcon(soapObject.getProperty( 
       9 
       ).toString())); map.put( 
       " 
       weatherDay 
       " 
       , weatherToday); map.put( 
       " 
       icons 
       " 
       ,icons); list.add(map);  
       // 
       ------------------------------------------------- 
         
        map 
       = 
       new 
        HashMap 
       < 
       String,Object 
       > 
       (); date 
       = 
       soapObject.getProperty( 
       13 
       ).toString(); String weatherTomorrow 
       = 
       " 
       明天: 
       " 
         
       + 
        date.split( 
       " 
         
       " 
       )[ 
       0 
       ]; weatherTomorrow 
       += 
       " 
       \n天气: 
       " 
       + 
        date.split( 
       " 
         
       " 
       )[ 
       1 
       ]; weatherTomorrow 
       += 
       " 
       \n气温: 
       " 
       + 
       soapObject.getProperty( 
       12 
       ).toString(); weatherTomorrow 
       += 
       " 
       \n风力: 
       " 
       + 
       soapObject.getProperty( 
       14 
       ).toString(); weatherTomorrow 
       += 
       " 
       \n 
       " 
       ; icons 
       = 
       new 
        ArrayList 
       < 
       Integer 
       > 
       (); icons.add(parseIcon(soapObject.getProperty( 
       15 
       ).toString())); icons.add(parseIcon(soapObject.getProperty( 
       16 
       ).toString())); map.put( 
       " 
       weatherDay 
       " 
       , weatherTomorrow); map.put( 
       " 
       icons 
       " 
       ,icons); list.add(map);  
       // 
       -------------------------------------------------------------- 
         
        map 
       = 
       new 
        HashMap 
       < 
       String,Object 
       > 
       (); date 
       = 
       soapObject.getProperty( 
       18 
       ).toString(); String weatherAfterTomorrow 
       = 
       " 
       后天: 
       " 
         
       + 
        date.split( 
       " 
         
       " 
       )[ 
       0 
       ]; weatherAfterTomorrow 
       += 
       " 
       \n天气: 
       " 
       + 
        date.split( 
       " 
         
       " 
       )[ 
       1 
       ]; weatherAfterTomorrow 
       += 
       " 
       \n气温: 
       " 
       + 
       soapObject.getProperty( 
       17 
       ).toString(); weatherAfterTomorrow 
       += 
       " 
       \n风力: 
       " 
       + 
       soapObject.getProperty( 
       19 
       ).toString(); weatherAfterTomorrow 
       += 
       " 
       \n 
       " 
       ; icons 
       = 
       new 
        ArrayList 
       < 
       Integer 
       > 
       (); icons.add(parseIcon(soapObject.getProperty( 
       20 
       ).toString())); icons.add(parseIcon(soapObject.getProperty( 
       21 
       ).toString())); map.put( 
       " 
       weatherDay 
       " 
       , weatherAfterTomorrow); map.put( 
       " 
       icons 
       " 
       ,icons); list.add(map);  
       // 
       -------------------------------------------------------------- 
         
        bean.setList(list);  
       return 
        bean; }  
       // 
       解析图标字符串 
         
         
       private 
         
       int 
        parseIcon(String data){  
       // 
        0.gif,返回名称0, 
         
         
       int 
        resID 
       = 
       32 
       ; String result 
       = 
       data.substring( 
       0 
       , data.length() 
       - 
       4 
       ).trim();  
       // 
        String []icon=data.split(".");  
       // 
        String result=icon[0].trim();  
       // 
        Log.e("this is the icon", result.trim()); 
         
         
       if 
       ( 
       ! 
       result.equals( 
       " 
       nothing 
       " 
       )){ resID 
       = 
       Integer.parseInt(result.trim()); }  
       return 
        resID;  
       // 
       return ("a_"+data).split(".")[0];  
         
        } }


以及帮助类:


View Code

以上就是我所作的查询天气预报的全部核心代码了,读者可以根据注释以及本文章了解下具体实现,相信很快就搞明白了,运行结果如下:

Android  web services详细使用_移动开发_03

Android  web services详细使用_json_04

Android  web services详细使用_List_05

Android  web services详细使用_List_06

Android  web services详细使用_List_07

 到此结束,下一节主要是socket通信了。


标签:web,getProperty,String,envelope,toString,services,new,Android,soapObject
From: https://blog.51cto.com/u_16034393/6886141

相关文章

  • Android 资源和国际化 [复制链接]
    Android资源和国际化[复制链接]资源是您在代码中使用到的并且在编译时被打包进您的应用程序的附加文件。Android支持多种不同的文件,包括XML、PNG和JPEG文件。XML文件的格式决定于其描述的内容。这些文件将描述文件支持的类型、语法或格式。  处于加载效率的考虑,资源被从......
  • android services 使用
    Android之Services【Services】一个Service是一个应用程序组件,它能完成长时间运行的操作在后台,并且不提供用户接口。另一个应用程序组件能开启一个service并且它将继续运行在后台即使用户转换到另一个应用程序。额外的,一个组件可以被绑定到一个service来和它交......
  • Android应用性能优化之分析工具
    Android应用性能优化之分析工具上一次记录了解决过度绘制的过程,这一次,想先弄清个概念性的东西,就是如何判断顺不顺畅?这东西其实最初我自己也觉得有点废话,用起来会卡就明显是不顺畅咯。但这东西就跟我很想吐槽很多应用一样,明明那么卡还放出来一样的道理。......
  • Google网站管理员:提升移动Web性…
    移动互联网已经在全球得到了广泛的应用。到2009年,有50%的新增的互联网访问都是来自手机设备的(eMarket,2008和2009)。来自Google的内部资料显示,随着移动浏览器的提升,用户的浏览习惯也在逐步改进。移动浏览器上的页面布局与桌面浏览器有着显著的差异,所以,想要在移动设备上开......
  • Android多线程及异步处理问题
    1、问题提出1)为何需要多线程?2)多线程如何实现?3)多线程机制的核心是啥?4)到底有多少种实现方式?2、问题分析1)究其为啥需要多线程的本质就是异步处理,直观一点说就是不要让用户感觉到“很卡”。eg:你点击按钮下载一首歌,......
  • Android多文件上传的原理
    android上面图片的上传可以用apache包里面的httpclient和MultipartEntity来上传图片,这种的上传方式的话由于都封装好了所以看不到HTTP协议里面具体是怎样上传的;其实图片的上传还可以用Java自带的HttpURLConnection来做上传处理,例如有一个PHP写的接收图片的POST接口http://localho......
  • 上百个Android开源项目分享
    上百个Android开源项目分享,希望对android开发有帮助。AndroidPDF阅读器http://sourceforge.net/projects/andpdf/files/个人记账工具OnMyMeanshttp://sourceforge.net/projects/onmymeans/developAndroid电池监控AndroidBatteryDoghttp://sourceforge.net/projects/a......
  • Android开发者应该深入学习的10个…
    1.Android团队提供的示例项目 如果不是从学习AndroidSDK中提供的那些样例代码开始,可能没有更好的方法来掌握在Android这个框架上开发。由Android的核心开发团队提供了15个优秀的示例项目,包含了游戏、图像处理、时间显示、开始菜单快捷方式等。 地址:http://code.google.com/p/......
  • Android JNI 编写方法
    JavaNativeInterface(JNI)标准是java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI是本地编程接口,它使得在Java虚拟机(VM)内部运行的Java代码能够与用其它编程语言(如C、C++和汇编语言)编写的应用程序和库进行交互操作。1.Java方式实现JNI,函数路径匹配......
  • Android图形系统之Surface、Surfac…
    1、SurfaceSurfaceextendsObjectimplementsParcelableClassOverviewHandleontoarawbufferthatisbeingmanagedbythescreencompositor.简单翻译:Surface是原始图像缓冲区(rawbuffer)的一个句柄,而原始图像缓冲区是由屏幕图像合成器(screencompositor)管理的。java.lan......