自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Android與服務(wù)器端數(shù)據(jù)交互

移動(dòng)開發(fā) Android
采用HttpClient向服務(wù)器端action請(qǐng)求數(shù)據(jù),當(dāng)然調(diào)用服務(wù)器端方法獲取數(shù)據(jù)并不止這一種WebService也可以為我們提供所需數(shù)據(jù),那么什么是webService呢?,它是一種基于SAOP協(xié)議的遠(yuǎn)程調(diào)用標(biāo)準(zhǔn),通過webservice可以將不同操作系統(tǒng)平臺(tái),不同語言,不同技術(shù)整合到一起。

實(shí)現(xiàn)Android與服務(wù)器端數(shù)據(jù)交互,我們?cè)赑C機(jī)器java客戶端中,需要一些庫,比如XFire,Axis2,CXF等等來支持訪問WebService,但是這些庫并不適合我們資源有限的android手機(jī)客戶端,做過JAVA ME的人都知道有KSOAP這個(gè)第三方的類庫,可以幫助我們獲取服務(wù)器端webService調(diào)用,當(dāng)然KSOAP已經(jīng)提供了基于android版本的jar包了,那么我們就開始吧:

首先下載KSOAP包:

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

然后新建android項(xiàng)目:并把下載的KSOAP包放在android項(xiàng)目的lib目錄下:右鍵->build path->configure build path--選擇Libraries,如圖:

以下分為七個(gè)步驟來調(diào)用WebService方法:

1、實(shí)例化SoapObject 對(duì)象,指定webService的命名空間(從相關(guān)WSDL文檔中可以查看命名空間),以及調(diào)用方法名稱。如:

  1. //命名空間        
  2.   private static final String serviceNameSpace="http://WebXml.com.cn/";      
  3. //調(diào)用方法(獲得支持的城市)       
  4.   private static final String getSupportCity="getSupportCity";    
  5. //實(shí)例化SoapObject對(duì)象           
  6.   SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);  

2、假設(shè)方法有參數(shù)的話,設(shè)置調(diào)用方法參數(shù)

  1. request.addProperty("參數(shù)名稱","參數(shù)值"); 

3、設(shè)置SOAP請(qǐng)求信息(參數(shù)部分為SOAP協(xié)議版本號(hào),與你要調(diào)用的webService中版本號(hào)一致):

  1. //獲得序列化的Envelope         
  2.     SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  3.     envelope.bodyOut=request

4、注冊(cè)Envelope,

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

5、構(gòu)建傳輸對(duì)象,并指明WSDL文檔URL:

  1. //請(qǐng)求URL     
  2.     private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";  
  3. //Android傳輸對(duì)象          
  4.        AndroidHttpTransport transport=new  AndroidHttpTransport(serviceURL);  
  5.       transport.debug=true

6、調(diào)用WebService(其中參數(shù)為1:命名空間+方法名稱,2:Envelope對(duì)象):

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

7、解析返回?cái)?shù)據(jù):

  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.   for(int i=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.      int index=temp.indexOf(",");  
  24.      list.add(temp.substring(0, index));  
  25.    }  
  26.  }    
  27.      return list;  

這樣就成功啦。那么現(xiàn)在我們就來測(cè)試下吧,這里有個(gè)地址提供webService天氣預(yù)報(bào)的服務(wù)的,我這里只提供獲取城市列表:

  1. //命名空間     
  2.  private static final String serviceNameSpace="http://WebXml.com.cn/";      
  3. //請(qǐng)求URL      
  4. private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";      
  5. //調(diào)用方法(獲得支持的城市)      
  6. private static final String getSupportCity="getSupportCity";      
  7. //調(diào)用城市的方法(需要帶參數(shù))     
  8.  private static final String getWeatherbyCityName="getWeatherbyCityName";      
  9. //調(diào)用省或者直轄市的方法(獲得支持的省份或直轄市)      
  10. private static final String getSupportProvince="getSupportProvince"

#p#

我們選擇獲取國內(nèi)外主要城市或者省份的方法吧:getSupportProvice,然后調(diào)用,你會(huì)發(fā)現(xiàn)瀏覽器返回給我們的是xml文檔:

  1. <?xml version="1.0" encoding="utf-8" ?> 
  2. <ArrayOfString xmlns: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>特別行政區(qū)</string>     
  7. <string>黑龍江</string>     
  8. <string>吉林</string>     
  9. <string>遼寧</string>    
  10. <string>內(nèi)蒙古</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>臺(tái)灣</string>     
  35. <string>亞洲</string>     
  36. <string>歐洲</string>     
  37. <string>非洲</string>     
  38. <string>北美洲</string>     
  39. <string>南美洲</string>     
  40. <string>大洋洲</string>     
  41. </ArrayOfString> 

我們可以用 listview來顯示:

那么下面我將給出全部代碼:

  1. public class WebServiceHelper {     
  2. //WSDL文檔中的命名空間     
  3. private static final   
  4. String targetNameSpace="http://WebXml.com.cn/";    //WSDL文檔中的URL      
  5. private static final   
  6. String WSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";             
  7. //需要調(diào)用的方法名(獲得本天氣預(yù)報(bào)Web Services支持的洲、國內(nèi)外省份和城市信息)      
  8. private static final String getSupportProvince="getSupportProvince";      
  9. //需要調(diào)用的方法名(獲得本天氣預(yù)報(bào)Web Services支持的城市信息,根據(jù)省份查詢城市集合:帶參數(shù))     
  10. private static final String getSupportCity="getSupportCity";      
  11. //根據(jù)城市或地區(qū)名稱查詢獲得未來三天內(nèi)天氣情況、現(xiàn)在的天氣實(shí)況、天氣和生活指數(shù)      
  12. private static final String getWeatherbyCityName="getWeatherbyCityName";      
  13. /********      
  14.  * 獲得州,國內(nèi)外省份和城市信息      
  15. * @return       
  16. */     
  17.  public  List<String> getProvince(){         
  18.  List<String>   
  19. provinces=new ArrayList<String>();         
  20.  String str="";         
  21.  SoapObject soapObject=new SoapObject(targetNameSpace,getSupportProvince);         
  22.  //request.addProperty("參數(shù)", "參數(shù)值");調(diào)用的方法參數(shù)與參數(shù)值(根據(jù)具體需要可選可不選)                  
  23. SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);         
  24. envelope.dotNet=true;          
  25. envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;  
  26.  AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);          
  27. //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);         
  28.  try {  
  29. httpTranstation.call(targetNameSpace+getSupportProvince, envelope);              
  30. SoapObject result=(SoapObject)envelope.getResponse();              
  31. //下面對(duì)結(jié)果進(jìn)行解析,結(jié)構(gòu)類似json對(duì)象             
  32.  //str=(String) result.getProperty(6).toString();                         
  33.  int count=result.getPropertyCount();             
  34.  for(int index=0;index<count;index++){                  
  35. provinces.add(result.getProperty(index).toString());             
  36.  }                     
  37.  } catch (IOException e) { // TODO Auto-generated catch block              
  38. e.printStackTrace();          
  39. } catch (XmlPullParserException e) { // TODO Auto-generated catch block              
  40. e.printStackTrace();         
  41.  }           
  42. return provinces;      
  43. }         
  44.  /**********       
  45. * 根據(jù)省份或者直轄市獲取天氣預(yù)報(bào)所支持的城市集合      
  46.  * @param province      
  47.  * @return       
  48. */      
  49. public  List<String> getCitys(String province){          
  50. List<String> citys=new ArrayList<String>();         
  51.  SoapObject soapObject=new SoapObject(targetNameSpace,getSupportCity);         
  52.  soapObject.addProperty("byProvinceName", province);          
  53. SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);         
  54.  envelope.dotNet=true;          
  55. envelope.setOutputSoapObject(soapObject);                 
  56. AndroidHttpTransport httpTransport=new AndroidHttpTransport(WSDL);          
  57. try {              
  58. httpTransport.call(targetNameSpace+getSupportCity, envelope);             
  59.  SoapObject result=(SoapObject)envelope.getResponse();             
  60.  int count=result.getPropertyCount();              
  61. for(int index=0;index<count;index++){                 
  62.  citys.add(result.getProperty(index).toString());            
  63.   }                     
  64.  } catch (IOException e) { // TODO Auto-generated catch block             
  65.  e.printStackTrace();         
  66.  } catch (XmlPullParserException e) { // TODO Auto-generated catch block              
  67. e.printStackTrace();          
  68. }          
  69.  return citys;    
  70.   }         
  71.  /***************************      
  72.  * 根據(jù)城市信息獲取天氣預(yù)報(bào)信息      
  73.  * @param city       
  74. * @return       
  75. ***************************/     
  76. public  WeatherBean getWeatherByCity(String city){                 
  77.  WeatherBean bean=new WeatherBean();         
  78.  SoapObject soapObject=new SoapObject(targetNameSpace,getWeatherbyCityName);          
  79. soapObject.addProperty("theCityName",city);//調(diào)用的方法參數(shù)與參數(shù)值(根據(jù)具體需要可選可不選)                 
  80.  SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);          
  81. envelope.dotNet=true;          
  82. envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;                         
  83. AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);          
  84. //或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);         
  85.  try {             
  86.  httpTranstation.call(targetNameSpace+getWeatherbyCityName, envelope);              
  87. SoapObject result=(SoapObject)envelope.getResponse();              
  88. //下面對(duì)結(jié)果進(jìn)行解析,結(jié)構(gòu)類似json對(duì)象              
  89. bean=parserWeather(result);                       
  90. } catch (IOException e) {              
  91. // TODO Auto-generated catch block              
  92. e.printStackTrace();          
  93. } catch (XmlPullParserException e) {       
  94.  // TODO Auto-generated catch block             
  95.  e.printStackTrace();         
  96.  }           
  97. return bean;     
  98.  }         
  99.  /**      
  100.  * 解析返回的結(jié)果      
  101.  * @param soapObject      
  102.  */     
  103.  protected   WeatherBean parserWeather(SoapObject soapObject){   
  104. WeatherBean bean=new WeatherBean();   
  105. List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();   
  106. Map<String,Object> map=new HashMap<String,Object>();//城市名         
  107.  bean.setCityName(soapObject.getProperty(1).toString());//城市簡(jiǎn)介  
  108. bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());   
  109. bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString()); //其他數(shù)據(jù) //日期,          
  110. String date=soapObject.getProperty(6).toString();      
  111. String weatherToday="今天:" + date.split(" ")[0];            
  112. weatherToday+="\n天氣:"+ date.split(" ")[1];           
  113. weatherToday+="\n氣溫:"+soapObject.getProperty(5).toString();         
  114. weatherToday+="\n風(fēng)力:"+soapObject.getProperty(7).toString();          
  115. weatherToday+="\n";   
  116.  List<Integer> icons=new ArrayList<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=new HashMap<String,Object>();           
  123. date=soapObject.getProperty(13).toString();          
  124. String weatherTomorrow="明天:" + date.split(" ")[0];            
  125. weatherTomorrow+="\n天氣:"+ date.split(" ")[1];           
  126. weatherTomorrow+="\n氣溫:"+soapObject.getProperty(12).toString();          
  127. weatherTomorrow+="\n風(fēng)力:"+soapObject.getProperty(14).toString();          
  128. weatherTomorrow+="\n";                  
  129. icons=new ArrayList<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=new HashMap<String,Object>();                  
  136.  date=soapObject.getProperty(18).toString();          
  137. String weatherAfterTomorrow="后天:" + date.split(" ")[0];            
  138. weatherAfterTomorrow+="\n天氣:"+ date.split(" ")[1];         
  139.   weatherAfterTomorrow+="\n氣溫:"+soapObject.getProperty(17).toString();         
  140.  weatherAfterTomorrow+="\n風(fēng)力:"+soapObject.getProperty(19).toString();         
  141.  weatherAfterTomorrow+="\n";                 
  142.  icons=new ArrayList<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.   return bean;     
  150.  }         //解析圖標(biāo)字符串       
  151. private int parseIcon(String data){          
  152. // 0.gif,返回名稱0,           
  153. int resID=32;           
  154. String result=data.substring(0, data.length()-4).trim();           
  155.  // String []icon=data.split(".");            
  156. // String result=icon[0].trim();            
  157. //   Log.e("this is the icon", result.trim());                      
  158.  if(!result.equals("nothing")){                 
  159. resID=Integer.parseInt(result.trim());           
  160.   }         
  161. return resID;          
  162.  //return ("a_"+data).split(".")[0];       
  163. }  

上就是我所作的查詢天氣預(yù)報(bào)的全部核心代碼了,讀者可以根據(jù)注釋以及本文章了解下具體實(shí)現(xiàn),相信很快就搞明白了,運(yùn)行結(jié)果如下:

到此結(jié)束,下一節(jié)主要是socket通信了。

【編輯推薦】

Android布局屬性詳解

Android環(huán)境變量的設(shè)置

Android Activity和Intent機(jī)制學(xué)習(xí)筆記

在Android應(yīng)用程序中使用Internet數(shù)據(jù)

Android用戶界面設(shè)計(jì)之創(chuàng)建列表視圖程序

責(zé)任編輯:zhaolei 來源: 互聯(lián)網(wǎng)
相關(guān)推薦

2012-10-15 13:40:15

IBMdw

2014-01-15 10:06:30

vFlash

2022-05-07 15:54:56

小熊派鴻蒙

2024-02-22 13:47:40

2012-05-07 13:55:41

JavaJava Web

2022-04-27 15:12:06

TCP服務(wù)器鴻蒙

2021-09-02 10:49:25

Node.jsPHP服務(wù)器開發(fā)

2014-11-14 11:03:56

微軟.NET

2023-06-30 08:00:00

漏洞網(wǎng)絡(luò)安全SSTI

2017-12-06 22:29:53

2013-12-25 11:01:16

JavaScript

2015-11-04 14:14:56

HTTP網(wǎng)絡(luò)協(xié)議

2009-06-10 16:25:02

2010-08-06 15:35:06

Flex服務(wù)器

2021-07-27 06:14:32

服務(wù)器端移動(dòng)端性能測(cè)試

2009-02-16 16:30:23

OperaTurbo服務(wù)器

2010-04-21 13:18:33

RAC負(fù)載均衡配置

2010-05-27 18:49:38

SVN入門

2010-08-27 10:23:26

DHCP服務(wù)器

2012-05-21 10:52:43

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)