Android 通过WebService调用天气预报接口


转自:http://blog.csdn.net/xiaanming/article/details/16871117

转帖请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/17483273),请尊重他人的辛勤劳动成果,谢谢!

相信大家在平常的开发中,对网络的操作用到HTTP协议比较多,通过我们使用Get或者Post的方法调用一个数据接口,然后服务器给我们返回JSON格式的数据,我们解析JSON数据然后展现给用户,相信很多人很喜欢服务器给我们返回JSON数据格式,因为他解析方便,也有一些JSON的解析库,例如Google提供的GSON,阿里巴巴的FastJson,不过还是推荐大家使用FastJson来解析,我自己开发中也是用FastJson来解析,FastJson的介绍http://code.alibabatech.com/wiki/display/FastJSON/Home,不过有时候我们用到WebService接口来获取数据, WebService是一种基于SOAP协议的远程调用标准,通过webservice可以将不同操作系统平台、不同语言、不同技术整合到一块。在Android SDK中并没有提供调用WebService的库,因此,需要使用第三方的SDK来调用WebService。PC版本的WEbservice客户端库非常丰富,例如Axis2,CXF等,但这些开发包对于Android系统过于庞大,也未必很容易移植到Android系统中。因此,这些开发包并不是在我们的考虑范围内。适合手机的WebService客户端的SDK有一些,比较常用的有Ksoap2,可以从http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2进行下载,将jar包加入到libs目录下就行了,接下来带大家来调用WebService接口

首先我们新建一个工程,取名WebServiceDemo,我们从http://www.webxml.com.cn/zh_cn/web_services.aspx来获取WebService接口,这里面有一些免费的WebService接口,我们就用里面的天气接口吧http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

我们新建一个WebService的工具类,用于对WebService接口的调用,以后遇到调用WebService直接拷贝来用就行了

  1. package com.example.webservicedemo;
  2. import java.io.IOException;
  3. import java.util.HashMap;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import org.ksoap2.SoapEnvelope;
  9. import org.ksoap2.serialization.SoapObject;
  10. import org.ksoap2.serialization.SoapSerializationEnvelope;
  11. import org.ksoap2.transport.HttpResponseException;
  12. import org.ksoap2.transport.HttpTransportSE;
  13. import org.xmlpull.v1.XmlPullParserException;
  14. import android.os.Handler;
  15. import android.os.Message;
  16. /**
  17. * 访问WebService的工具类,
  18. *
  19. * @see http://blog.csdn.net/xiaanming
  20. *
  21. * @author xiaanming
  22. *
  23. */
  24. public class WebServiceUtils {
  25. public static final String WEB_SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
  26. // 含有3个线程的线程池
  27. private static final ExecutorService executorService = Executors
  28. .newFixedThreadPool(3);
  29. // 命名空间
  30. private static final String NAMESPACE = "http://WebXml.com.cn/";
  31. /**
  32. *
  33. * @param url
  34. * WebService服务器地址
  35. * @param methodName
  36. * WebService的调用方法名
  37. * @param properties
  38. * WebService的参数
  39. * @param webServiceCallBack
  40. * 回调接口
  41. */
  42. public static void callWebService(String url, final String methodName,
  43. HashMap<String, String> properties,
  44. final WebServiceCallBack webServiceCallBack) {
  45. // 创建HttpTransportSE对象,传递WebService服务器地址
  46. final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
  47. // 创建SoapObject对象
  48. SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
  49. // SoapObject添加参数
  50. if (properties != null) {
  51. for (Iterator<Map.Entry<String, String>> it = properties.entrySet()
  52. .iterator(); it.hasNext();) {
  53. Map.Entry<String, String> entry = it.next();
  54. soapObject.addProperty(entry.getKey(), entry.getValue());
  55. }
  56. }
  57. // 实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号
  58. final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
  59. SoapEnvelope.VER11);
  60. // 设置是否调用的是.Net开发的WebService
  61. soapEnvelope.setOutputSoapObject(soapObject);
  62. soapEnvelope.dotNet = true;
  63. httpTransportSE.debug = true;
  64. // 用于子线程与主线程通信的Handler
  65. final Handler mHandler = new Handler() {
  66. @Override
  67. public void handleMessage(Message msg) {
  68. super.handleMessage(msg);
  69. // 将返回值回调到callBack的参数中
  70. webServiceCallBack.callBack((SoapObject) msg.obj);
  71. }
  72. };
  73. // 开启线程去访问WebService
  74. executorService.submit(new Runnable() {
  75. @Override
  76. public void run() {
  77. SoapObject resultSoapObject = null;
  78. try {
  79. httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
  80. if (soapEnvelope.getResponse() != null) {
  81. // 获取服务器响应返回的SoapObject
  82. resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
  83. }
  84. } catch (HttpResponseException e) {
  85. e.printStackTrace();
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. } catch (XmlPullParserException e) {
  89. e.printStackTrace();
  90. } finally {
  91. // 将获取的消息利用Handler发送到主线程
  92. mHandler.sendMessage(mHandler.obtainMessage(0,
  93. resultSoapObject));
  94. }
  95. }
  96. });
  97. }
  98. /**
  99. *
  100. *
  101. * @author xiaanming
  102. *
  103. */
  104. public interface WebServiceCallBack {
  105. public void callBack(SoapObject result);
  106. }
  107. }

我们通过调用里面的callWebService(String url, final String methodName,HashMap<String, String> properties,final WebServiceCallBack webServiceCallBack)就可以来获取我们想要的数据,现在讲解下里面的实现思路

  • 创建HttpTransportsSE对象。通过HttpTransportsSE类的构造方法可以指定WebService的WSDL文档的URL
  • 创建SoapObject对象,里面的参数分别是WebService的命名空间和调用方法名
  • 设置调用方法的参数值,如果没有参数,就不设置,有参数的话调用SoapObject对象的addProperty(String name, Object value)方法将参数加入到SoapObject对象中
  • 实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号,将上面的SoapObject对象通过setOutputSoapObject(Object soapObject)设置到里面,并设置是否调用的是.Net开发的WebService和是否debug等信息
  • 因为涉及到网络操作,所以我们使用了线程池来异步操作调用WebService接口,我们在线程中调用HttpTransportsSE对象的call(String soapAction, SoapEnvelope envelope)方法就能实现对WebService的调用,并且通过soapEnvelope.bodyIn获取WebService返回的信息,但是返回的信息是在子线程中,我们需要利用Handler来实现子线程与主线程进行转换,然后在Handler的handleMessage(Message msg)中将结果回调到callBack的参数中,总体思路就是这个样子,接下来我们来使用这个工具类吧

我们先用一个ListView来显示所有的省份,然后点击每个省进去到市。市也用一个ListView来显示,最后点击市用TextView来显示获取的WebService天气情况,思路很简单

用来显示省份的布局,里面只有一个ListView

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <ListView
  6. android:id="@+id/province_list"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:cacheColorHint="@android:color/transparent"
  10. android:fadingEdge="none" >
  11. </ListView>
  12. </RelativeLayout>
接下来就是Activity的代码,先用工具类调用WebService方法,然后在回调方法callBack(SoapObject result)中解析数据到一个List<String>中,在设置ListView的适配器

  1. package com.example.webservicedemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.ksoap2.serialization.SoapObject;
  5. import android.app.Activity;
  6. import android.content.Intent;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.widget.AdapterView;
  10. import android.widget.AdapterView.OnItemClickListener;
  11. import android.widget.ArrayAdapter;
  12. import android.widget.ListView;
  13. import android.widget.Toast;
  14. import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;
  15. /**
  16. * 显示天气省份的Activity
  17. *
  18. * @see http://blog.csdn.net/xiaanming
  19. *
  20. * @author xiaanming
  21. *
  22. */
  23. public class MainActivity extends Activity {
  24. private List<String> provinceList = new ArrayList<String>();
  25. @Override
  26. public void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. init();
  30. }
  31. private void init() {
  32. final ListView mProvinceList = (ListView) findViewById(R.id.province_list);
  33. //显示进度条
  34. ProgressDialogUtils.showProgressDialog(this, "数据加载中...");
  35. //通过工具类调用WebService接口
  36. WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getSupportProvince", null, new WebServiceCallBack() {
  37. //WebService接口返回的数据回调到这个方法中
  38. @Override
  39. public void callBack(SoapObject result) {
  40. //关闭进度条
  41. ProgressDialogUtils.dismissProgressDialog();
  42. if(result != null){
  43. provinceList = parseSoapObject(result);
  44. mProvinceList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, provinceList));
  45. }else{
  46. Toast.makeText(MainActivity.this, "获取WebService数据错误", Toast.LENGTH_SHORT).show();
  47. }
  48. }
  49. });
  50. mProvinceList.setOnItemClickListener(new OnItemClickListener() {
  51. @Override
  52. public void onItemClick(AdapterView<?> parent, View view,
  53. int position, long id) {
  54. Intent intent = new Intent(MainActivity.this, CityActivity.class);
  55. intent.putExtra("province", provinceList.get(position));
  56. startActivity(intent);
  57. }
  58. });
  59. }
  60. /**
  61. * 解析SoapObject对象
  62. * @param result
  63. * @return
  64. */
  65. private List<String> parseSoapObject(SoapObject result){
  66. List<String> list = new ArrayList<String>();
  67. SoapObject provinceSoapObject = (SoapObject) result.getProperty("getSupportProvinceResult");
  68. if(provinceSoapObject == null) {
  69. return null;
  70. }
  71. for(int i=0; i<provinceSoapObject.getPropertyCount(); i++){
  72. list.add(provinceSoapObject.getProperty(i).toString());
  73. }
  74. return list;
  75. }
  76. }
点击省份进入该省份下面的市。也用一个ListView来显示市的数据,布局跟上面一样,Activity里面的代码也差不多相似,我就不过多说明了,直接看代码

  1. package com.example.webservicedemo;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import org.ksoap2.serialization.SoapObject;
  6. import android.app.Activity;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.AdapterView;
  11. import android.widget.AdapterView.OnItemClickListener;
  12. import android.widget.ArrayAdapter;
  13. import android.widget.ListView;
  14. import android.widget.Toast;
  15. import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;
  16. /**
  17. * 显示城市的Activity
  18. *
  19. * @see http://blog.csdn.net/xiaanming
  20. *
  21. * @author xiaanming
  22. *
  23. */
  24. public class CityActivity extends Activity {
  25. private List<String> cityStringList;
  26. @Override
  27. public void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. init();
  31. }
  32. private void init() {
  33. final ListView mCityList = (ListView) findViewById(R.id.province_list);
  34. //显示进度条
  35. ProgressDialogUtils.showProgressDialog(this, "数据加载中...");
  36. //添加参数
  37. HashMap<String, String> properties = new HashMap<String, String>();
  38. properties.put("byProvinceName", getIntent().getStringExtra("province"));
  39. WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getSupportCity", properties, new WebServiceCallBack() {
  40. @Override
  41. public void callBack(SoapObject result) {
  42. ProgressDialogUtils.dismissProgressDialog();
  43. if(result != null){
  44. cityStringList = parseSoapObject(result);
  45. mCityList.setAdapter(new ArrayAdapter<String>(CityActivity.this, android.R.layout.simple_list_item_1, cityStringList));
  46. }else{
  47. Toast.makeText(CityActivity.this, "获取WebService数据错误", Toast.LENGTH_SHORT).show();
  48. }
  49. }
  50. });
  51. mCityList.setOnItemClickListener(new OnItemClickListener() {
  52. @Override
  53. public void onItemClick(AdapterView<?> parent, View view,
  54. int position, long id) {
  55. Intent intent = new Intent(CityActivity.this, WeatherActivity.class);
  56. intent.putExtra("city", cityStringList.get(position));
  57. startActivity(intent);
  58. }
  59. });
  60. }
  61. /**
  62. * 解析SoapObject对象
  63. * @param result
  64. * @return
  65. */
  66. private List<String> parseSoapObject(SoapObject result){
  67. List<String> list = new ArrayList<String>();
  68. SoapObject provinceSoapObject = (SoapObject) result.getProperty("getSupportCityResult");
  69. for(int i=0; i<provinceSoapObject.getPropertyCount(); i++){
  70. String cityString = provinceSoapObject.getProperty(i).toString();
  71. list.add(cityString.substring(0, cityString.indexOf("(")).trim());
  72. }
  73. return list;
  74. }
  75. }
接下来就是点击相对应的城市调用WebService接口来获取该城市下面的天气详情啦,为了简单起见,我用一个TextView来显示天气信息,因为天气信息很多,一个屏幕显示不完,所以我们考虑在外面加一个ScrollView来进行滚动

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent" >
  5. <ScrollView
  6. android:layout_width="fill_parent"
  7. android:layout_height="fill_parent" >
  8. <LinearLayout
  9. android:layout_width="match_parent"
  10. android:layout_height="match_parent" >
  11. <TextView
  12. android:id="@+id/weather"
  13. android:textColor="#336598"
  14. android:textSize="16sp"
  15. android:layout_width="match_parent"
  16. android:layout_height="match_parent" />
  17. </LinearLayout>
  18. </ScrollView>
  19. </RelativeLayout>
Activity的代码就不做过多说明,跟上面的大同小异

  1. package com.example.webservicedemo;
  2. import java.util.HashMap;
  3. import org.ksoap2.serialization.SoapObject;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.widget.TextView;
  7. import android.widget.Toast;
  8. import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;
  9. /**
  10. * 显示天气的Activity
  11. *
  12. * @see http://blog.csdn.net/xiaanming
  13. *
  14. * @author xiaanming
  15. *
  16. */
  17. public class WeatherActivity extends Activity{
  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.weather_layout);
  22. init();
  23. }
  24. private void init() {
  25. final TextView mTextWeather = (TextView) findViewById(R.id.weather);
  26. ProgressDialogUtils.showProgressDialog(this, "数据加载中...");
  27. HashMap<String, String> properties = new HashMap<String, String>();
  28. properties.put("theCityName", getIntent().getStringExtra("city"));
  29. WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getWeatherbyCityName", properties, new WebServiceCallBack() {
  30. @Override
  31. public void callBack(SoapObject result) {
  32. ProgressDialogUtils.dismissProgressDialog();
  33. if(result != null){
  34. SoapObject detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");
  35. StringBuilder sb = new StringBuilder();
  36. for(int i=0; i<detail.getPropertyCount(); i++){
  37. sb.append(detail.getProperty(i)).append("\r\n");
  38. }
  39. mTextWeather.setText(sb.toString());
  40. }else{
  41. Toast.makeText(WeatherActivity.this, "获取WebService数据错误", Toast.LENGTH_SHORT).show();
  42. }
  43. }
  44. });
  45. }
  46. }
到这里我们就完成了编码工作,在运行程序之前我们需要在AndroidManifest.xml注册Activity,以及添加访问网络的权限

  1. <application
  2. android:icon="@drawable/ic_launcher"
  3. android:label="@string/app_name"
  4. android:theme="@style/AppTheme" >
  5. <activity
  6. android:name="com.example.webservicedemo.MainActivity"
  7. android:label="@string/title_activity_main" >
  8. <intent-filter>
  9. <action android:name="android.intent.action.MAIN" />
  10. <category android:name="android.intent.category.LAUNCHER" />
  11. </intent-filter>
  12. </activity>
  13. <activity android:name=".CityActivity"/>
  14. <activity android:name=".WeatherActivity"></activity>
  15. </application>
  16. <uses-permission android:name="android.permission.INTERNET"/>
运行结果:



省份,城市列表可以加上A-Z的排序功能,可以参考下Android实现ListView的A-Z字母排序和过滤搜索功能,实现汉字转成拼音,我这里就不添加了,需要添加的朋友自行实现,好了,今天的讲解到此结束,有疑问的朋友请在下面留言。

项目源码,点击下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值