您所在的位置:移动开发 > Android > Android与服务器端数据交互(1)

Android与服务器端数据交互(1)

2011-06-07 16:01 佚名 互联网 我要评论(0) 字号: T | T

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

AD:


实现Android与服务器端数据交互,我们在PC机器java客户端中,需要一些库,比如XFire,Axis2,CXF等等来支持访问WebService,但是这些库并不适合我们资源有限的android手机客户端,做过JAVA ME的人都知道有KSOAP这个第三方的类库,可以帮助我们获取服务器端webService调用,当然KSOAP已经提供了基于android版本的jar包了,那么我们就开始吧:

首先下载KSOAP包:

                
  1. ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar

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

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

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

                
  1. //命名空间
  2. privatestaticfinalStringserviceNameSpace="http://WebXml.com.cn/";
  3. //调用方法(获得支持的城市)
  4. privatestaticfinalStringgetSupportCity="getSupportCity";
  5. //实例化SoapObject对象
  6. SoapObjectrequest=newSoapObject(serviceNameSpace,getSupportCity);

2、假设方法有参数的话,设置调用方法参数

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

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

                
  1. //获得序列化的Envelope
  2. SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
  3. envelope.bodyOut=request;

4、注册Envelope,

                
  1. (newMarshalBase64()).register(envelope);

5、构建传输对象,并指明WSDL文档URL:

                
  1. //请求URL
  2. privatestaticfinalStringserviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  3. //Android传输对象
  4. AndroidHttpTransporttransport=newAndroidHttpTransport(serviceURL);
  5. transport.debug=true;

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

                
  1. transport.call(serviceNameSpace+getWeatherbyCityName,envelope);

7、解析返回数据:

                
  1. if(envelope.getResponse()!=null){
  2. returnparse(envelope.bodyIn.toString());
  3. }
  4. /**************
  5. *解析XML
  6. *@paramstr
  7. *@return
  8. */
  9. privatestaticList<String>parse(Stringstr){
  10. Stringtemp;
  11. List<String>list=newArrayList<String>();
  12. if(str!=null&&str.length()>0){
  13. intstart=str.indexOf("string");
  14. intend=str.lastIndexOf(";");
  15. temp=str.substring(start,end-3);
  16. String[]test=temp.split(";");
  17. for(inti=0;i<test.length;i++){
  18. if(i==0){
  19. temp=test[i].substring(7);
  20. }else{
  21. temp=test[i].substring(8);
  22. }
  23. intindex=temp.indexOf(",");
  24. list.add(temp.substring(0,index));
  25. }
  26. }
  27. returnlist;
  28. }

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

  1. //命名空间
  2. privatestaticfinalStringserviceNameSpace="http://WebXml.com.cn/";
  3. //请求URL
  4. privatestaticfinalStringserviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  5. //调用方法(获得支持的城市)
  6. privatestaticfinalStringgetSupportCity="getSupportCity";
  7. //调用城市的方法(需要带参数)
  8. privatestaticfinalStringgetWeatherbyCityName="getWeatherbyCityName";
  9. //调用省或者直辖市的方法(获得支持的省份或直辖市)
  10. privatestaticfinalStringgetSupportProvince="getSupportProvince";
                                           

您所在的位置:移动开发 > Android > Android与服务器端数据交互(2)

Android与服务器端数据交互(2)

2011-06-07 16:01 佚名 互联网 我要评论(0) 字号: T | T

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

AD:


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

                                    
    1. <?xmlversion="1.0"encoding="utf-8"?>
    2. <ArrayOfStringxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    4. xmlns="http://WebXml.com.cn/">
    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. <string>南美洲</string>
    40. <string>大洋洲</string>
    41. </ArrayOfString>

    我们可以用 listview来显示:

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

                                    
    1. publicclassWebServiceHelper{
    2. //WSDL文档中的命名空间
    3. privatestaticfinal
    4. StringtargetNameSpace="http://WebXml.com.cn/";//WSDL文档中的URL
    5. privatestaticfinal
    6. StringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
    7. //需要调用的方法名(获得本天气预报WebServices支持的洲、国内外省份和城市信息)
    8. privatestaticfinalStringgetSupportProvince="getSupportProvince";
    9. //需要调用的方法名(获得本天气预报WebServices支持的城市信息,根据省份查询城市集合:带参数)
    10. privatestaticfinalStringgetSupportCity="getSupportCity";
    11. //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
    12. privatestaticfinalStringgetWeatherbyCityName="getWeatherbyCityName";
    13. /********
    14. *获得州,国内外省份和城市信息
    15. *@return
    16. */
    17. publicList<String>getProvince(){
    18. List<String>
    19. provinces=newArrayList<String>();
    20. Stringstr="";
    21. SoapObjectsoapObject=newSoapObject(targetNameSpace,getSupportProvince);
    22. //request.addProperty("参数","参数值");调用的方法参数与参数值(根据具体需要可选可不选)
    23. SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
    24. envelope.dotNet=true;
    25. envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
    26. AndroidHttpTransporthttpTranstation=newAndroidHttpTransport(WSDL);
    27. //或者HttpTransportSEhttpTranstation=newHttpTransportSE(WSDL);
    28. try{
    29. httpTranstation.call(targetNameSpace+getSupportProvince,envelope);
    30. SoapObjectresult=(SoapObject)envelope.getResponse();
    31. //下面对结果进行解析,结构类似json对象
    32. //str=(String)result.getProperty(6).toString();
    33. intcount=result.getPropertyCount();
    34. for(intindex=0;index<count;index++){
    35. provinces.add(result.getProperty(index).toString());
    36. }
    37. }catch(IOExceptione){//TODOAuto-generatedcatchblock
    38. e.printStackTrace();
    39. }catch(XmlPullParserExceptione){//TODOAuto-generatedcatchblock
    40. e.printStackTrace();
    41. }
    42. returnprovinces;
    43. }
    44. /**********
    45. *根据省份或者直辖市获取天气预报所支持的城市集合
    46. *@paramprovince
    47. *@return
    48. */
    49. publicList<String>getCitys(Stringprovince){
    50. List<String>citys=newArrayList<String>();
    51. SoapObjectsoapObject=newSoapObject(targetNameSpace,getSupportCity);
    52. soapObject.addProperty("byProvinceName",province);
    53. SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
    54. envelope.dotNet=true;
    55. envelope.setOutputSoapObject(soapObject);
    56. AndroidHttpTransporthttpTransport=newAndroidHttpTransport(WSDL);
    57. try{
    58. httpTransport.call(targetNameSpace+getSupportCity,envelope);
    59. SoapObjectresult=(SoapObject)envelope.getResponse();
    60. intcount=result.getPropertyCount();
    61. for(intindex=0;index<count;index++){
    62. citys.add(result.getProperty(index).toString());
    63. }
    64. }catch(IOExceptione){//TODOAuto-generatedcatchblock
    65. e.printStackTrace();
    66. }catch(XmlPullParserExceptione){//TODOAuto-generatedcatchblock
    67. e.printStackTrace();
    68. }
    69. returncitys;
    70. }
    71. /***************************
    72. *根据城市信息获取天气预报信息
    73. *@paramcity
    74. *@return
    75. ***************************/
    76. publicWeatherBeangetWeatherByCity(Stringcity){
    77. WeatherBeanbean=newWeatherBean();
    78. SoapObjectsoapObject=newSoapObject(targetNameSpace,getWeatherbyCityName);
    79. soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)
    80. SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
    81. envelope.dotNet=true;
    82. envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
    83. AndroidHttpTransporthttpTranstation=newAndroidHttpTransport(WSDL);
    84. //或者HttpTransportSEhttpTranstation=newHttpTransportSE(WSDL);
    85. try{
    86. httpTranstation.call(targetNameSpace+getWeatherbyCityName,envelope);
    87. SoapObjectresult=(SoapObject)envelope.getResponse();
    88. //下面对结果进行解析,结构类似json对象
    89. bean=parserWeather(result);
    90. }catch(IOExceptione){
    91. //TODOAuto-generatedcatchblock
    92. e.printStackTrace();
    93. }catch(XmlPullParserExceptione){
    94. //TODOAuto-generatedcatchblock
    95. e.printStackTrace();
    96. }
    97. returnbean;
    98. }
    99. /**
    100. *解析返回的结果
    101. *@paramsoapObject
    102. */
    103. protectedWeatherBeanparserWeather(SoapObjectsoapObject){
    104. WeatherBeanbean=newWeatherBean();
    105. List<Map<String,Object>>list=newArrayList<Map<String,Object>>();
    106. Map<String,Object>map=newHashMap<String,Object>();//城市名
    107. bean.setCityName(soapObject.getProperty(1).toString());//城市简介
    108. bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
    109. bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString());//其他数据//日期,
    110. Stringdate=soapObject.getProperty(6).toString();
    111. StringweatherToday="今天:"+date.split("")[0];
    112. weatherToday+="\n天气:"+date.split("")[1];
    113. weatherToday+="\n气温:"+soapObject.getProperty(5).toString();
    114. weatherToday+="\n风力:"+soapObject.getProperty(7).toString();
    115. weatherToday+="\n";
    116. List<Integer>icons=newArrayList<Integer>();
    117. icons.add(parseIcon(soapObject.getProperty(8).toString()));
    118. icons.add(parseIcon(soapObject.getProperty(9).toString()));
    119. map.put("weatherDay",weatherToday);
    120. map.put("icons",icons);
    121. list.add(map);
    122. map=newHashMap<String,Object>();
    123. date=soapObject.getProperty(13).toString();
    124. StringweatherTomorrow="明天:"+date.split("")[0];
    125. weatherTomorrow+="\n天气:"+date.split("")[1];
    126. weatherTomorrow+="\n气温:"+soapObject.getProperty(12).toString();
    127. weatherTomorrow+="\n风力:"+soapObject.getProperty(14).toString();
    128. weatherTomorrow+="\n";
    129. icons=newArrayList<Integer>();
    130. icons.add(parseIcon(soapObject.getProperty(15).toString()));
    131. icons.add(parseIcon(soapObject.getProperty(16).toString()));
    132. map.put("weatherDay",weatherTomorrow);
    133. map.put("icons",icons);
    134. list.add(map);
    135. map=newHashMap<String,Object>();
    136. date=soapObject.getProperty(18).toString();
    137. StringweatherAfterTomorrow="后天:"+date.split("")[0];
    138. weatherAfterTomorrow+="\n天气:"+date.split("")[1];
    139. weatherAfterTomorrow+="\n气温:"+soapObject.getProperty(17).toString();
    140. weatherAfterTomorrow+="\n风力:"+soapObject.getProperty(19).toString();
    141. weatherAfterTomorrow+="\n";
    142. icons=newArrayList<Integer>();
    143. icons.add(parseIcon(soapObject.getProperty(20).toString()));
    144. icons.add(parseIcon(soapObject.getProperty(21).toString()));
    145. map.put("weatherDay",weatherAfterTomorrow);
    146. map.put("icons",icons);
    147. list.add(map);
    148. bean.setList(list);
    149. returnbean;
    150. }//解析图标字符串
    151. privateintparseIcon(Stringdata){
    152. //0.gif,返回名称0,
    153. intresID=32;
    154. Stringresult=data.substring(0,data.length()-4).trim();
    155. //String[]icon=data.split(".");
    156. //Stringresult=icon[0].trim();
    157. //Log.e("thisistheicon",result.trim());
    158. if(!result.equals("nothing")){
    159. resID=Integer.parseInt(result.trim());
    160. }
    161. returnresID;
    162. //return("a_"+data).split(".")[0];
    163. }
    164. }

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

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

    更多相关文章

    1. Android单元测试之Testing和Instrumentation
    2. NDK开发历程(一):android native code的调试方法
    3. Android(安卓)ListView拖动时背景变黑的解决方法
    4. Android恶意代码分析与渗透测试
    5. Android日常整理(一)---android返回键、Fragment、android分割线、
    6. 你的Android,我的Android
    7. android ------ AAPT2 error: check logs for details解决方法
    8. Android(安卓)小项目之--SQLite 使用法门 (附源码)
    9. Android开发艺术探索——第二章:IPC机制(上)

    随机推荐

    1. [置顶] Android(安卓)定时任务的多种实现
    2. Android应用启动后自动创建桌面快捷方式
    3. Android(安卓)SystemProperties.get()和S
    4. Android(安卓)add prebuilt lib(*.so) to
    5. Android中的消息机制
    6. android之sqliteDatabase,sqliteOpenHelp
    7. Google Android操作系统内核编译图文教程
    8. 那些你不知道的Android小事儿
    9. Android读写XML(中)——SAX
    10. unable to access android sdk add-on li