采用HttpClient向服务器端action请求数据,当然调用服务器端方法获取数据并不止这一种WebService也可以为我们提供所需数据,那么什么是webService呢?,它是一种基于SAOP协议的远程调用标准,通过webservice可以将不同操作系统平台,不同语言,不同技术整合到一起。
实现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目录下:右键->buildpath->configure build path--选择Libraries,如图:
以下分为七个步骤来调用WebService方法:
1、实例化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);
2、假设方法有参数的话,设置调用方法参数
1. request.addProperty("参数名称","参数值");
3、设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):
1. //获得序列化的Envelope
2. SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
3. envelope.bodyOut=request;
4、注册Envelope,
1. (new MarshalBase64()).register(envelope);
5、构建传输对象,并指明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;
6、调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
1. transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
7、解析返回数据:
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;
28.}
这样就成功啦。那么现在我们就来测试下吧,这里有个地址提供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";
我们选择获取国内外主要城市或者省份的方法吧:getSupportProvice,然后调用,你会发现浏览器返回给我们的是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>特别行政区</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. 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. //需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)
8. private static final String getSupportProvince="getSupportProvince";
9. //需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)
10.private static final String getSupportCity="getSupportCity";
11.//根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
12.private static final String getWeatherbyCityName="getWeatherbyCityName";
13./********
14. * 获得州,国内外省份和城市信息
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("参数", "参数值");调用的方法参数与参数值(根据具体需要可选可不选)
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.//下面对结果进行解析,结构类似json对象
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.* 根据省份或者直辖市获取天气预报所支持的城市集合
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. * 根据城市信息获取天气预报信息
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);//调用的方法参数与参数值(根据具体需要可选可不选)
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.//下面对结果进行解析,结构类似json对象
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. * 解析返回的结果
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());//城市简介
108. bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
109. bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString()); //其他数据 //日期,
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风力:"+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风力:"+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风力:"+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. } //解析图标字符串
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. }
164. }
上就是我所作的查询天气预报的全部核心代码了,读者可以根据注释以及本文章了解下具体实现,相信很快就搞明白了,运行结果如下:
到此结束,下一节主要是socket通信了。