Android:WebService使用实例

分类:Android 6156人阅读 评论(14) 收藏 举报

最近刚刚开始学习使用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,如图:

同时,只添加jar包肯能是不够的,需要添加class folder,即可以再工程的libs文件夹中加入下载的KSOAP包,如图:

Android:WebService_第1张图片

Android:WebService_第2张图片

环境配好之后可以用下面七个步骤来调用WebService方法:

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

//命名空间
privatestaticfinal String serviceNameSpace="http://WebXml.com.cn/";
//调用方法(获得支持的城市)
privatestaticfinal String getSupportCity="getSupportCity";

//实例化SoapObject对象
SoapObject request=newSoapObject(serviceNameSpace, getSupportCity);

第二步:假设方法有参数的话,设置调用方法参数:

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

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

//获得序列化的Envelope
SoapSerializationEnvelope envelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;

第四步:注册Envelope

(newMarshalBase64()).register(envelope);

第五步:构建传输对象,并指明WSDL文档URL

//请求URL
privatestaticfinal String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=newAndroidHttpTransport(serviceURL);
transport.debug=true;

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

transport.call(serviceNameSpace+getWeatherbyCityName, envelope);

第七步:解析返回数据:

if(envelope.getResponse()!=null){
returnparse(envelope.bodyIn.toString());
}

这里有个地址提供webService天气预报的服务网站,在浏览器中输入网站:http://www.webxml.com.cn/webservices/weatherwebservice.asmx可以看到该网站提供的

调用方法,点进去之后可以看到调用时需要输入的参数,当然有的不需要参数,例如:getSupportProvince,而getSupportCity需要输入查找的省份名,getWeatherbyCityName需要输入查找的城市名。接下来我们就利用这三个接口获得数据,并做出显示:

获得本天气预报Web Service支持的洲,国内外省份和城市信息:

[html] view plain copy print ?
  1. publicclassMainActivityextendsActivity{
  2. //WSDL文档中的命名空间
  3. privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
  4. //WSDL文档中的URL
  5. privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
  6. //需要调用的方法名(获得本天气预报WebServices支持的洲、国内外省份和城市信息)
  7. privatestaticfinalStringgetSupportProvince="getSupportProvince";
  8. privateList<Map<String,String>>listItems;
  9. privateListViewmListView;
  10. @Override
  11. protectedvoidonCreate(BundlesavedInstanceState){
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. listItems=newArrayList<Map<String,String>>();
  15. mListView=(ListView)findViewById(R.id.province_list);
  16. newNetAsyncTask().execute();
  17. mListView.setOnItemClickListener(newAdapterView.OnItemClickListener(){
  18. @Override
  19. publicvoidonItemClick(AdapterView<?>parent,Viewview,
  20. intposition,longid){
  21. StringmProvinceName=listItems.get(position).get("province");
  22. Log.d("ProvinceName",mProvinceName);
  23. Intentintent=newIntent();
  24. intent.putExtra("Pname",mProvinceName);
  25. intent.setClass(MainActivity.this,CityActivity.class);
  26. startActivity(intent);
  27. }
  28. });
  29. }
  30. classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
  31. @Override
  32. protectedvoidonPostExecute(Stringresult){
  33. if(result.equals("success")){
  34. //列表适配器
  35. SimpleAdaptersimpleAdapter=newSimpleAdapter(MainActivity.this,listItems,R.layout.province_item,
  36. newString[]{"province"},newint[]{R.id.province});
  37. mListView.setAdapter(simpleAdapter);
  38. }
  39. super.onPostExecute(result);
  40. }
  41. @Override
  42. protectedStringdoInBackground(Object...params){
  43. //根据命名空间和方法得到SoapObject对象
  44. SoapObjectsoapObject=newSoapObject(targetNameSpace,
  45. getSupportProvince);
  46. //通过SOAP1.1协议得到envelop对象
  47. SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(
  48. SoapEnvelope.VER11);
  49. //将soapObject对象设置为envelop对象,传出消息
  50. envelop.dotNet=true;
  51. envelop.setOutputSoapObject(soapObject);
  52. //或者envelop.bodyOut=soapObject;
  53. HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
  54. //开始调用远程方法
  55. try{
  56. httpSE.call(targetNameSpace+getSupportProvince,envelop);
  57. //得到远程方法返回的SOAP对象
  58. SoapObjectresultObj=(SoapObject)envelop.getResponse();
  59. //得到服务器传回的数据
  60. intcount=resultObj.getPropertyCount();
  61. for(inti=0;i<count;i++){
  62. Map<String,String>listItem=newHashMap<String,String>();
  63. listItem.put("province",resultObj.getProperty(i).toString());
  64. listItems.add(listItem);
  65. }
  66. }catch(IOExceptione){
  67. e.printStackTrace();
  68. return"IOException";
  69. }catch(XmlPullParserExceptione){
  70. e.printStackTrace();
  71. return"XmlPullParserException";
  72. }
  73. return"success";
  74. }
  75. }
  76. }

显示省份列表的activity_main.xml文件:

[html] view plain copy print ?
  1. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="fill_parent"
  3. android:layout_height="match_parent">
  4. <ListView
  5. android:id="@+id/province_list"
  6. android:layout_width="fill_parent"
  7. android:layout_height="fill_parent"/>
  8. </LinearLayout>


列表中选项显示的province_item.xml文件:

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:id="@+id/province"
  8. android:layout_width="fill_parent"
  9. android:layout_height="match_parent"
  10. android:textSize="20sp"/>
  11. </LinearLayout>


效果图,如图:

查询本天气预报Web Services支持的国内外城市或地区信息:

[java] view plain copy print ?
  1. publicclassCityActivityextendsActivity{
  2. //WSDL文档中的命名空间
  3. privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
  4. //WSDL文档中的URL
  5. privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
  6. //需要调用的方法名(获得本天气预报WebServices支持的城市信息,根据省份查询城市集合:带参数)
  7. privatestaticfinalStringgetSupportCity="getSupportCity";
  8. privateList<Map<String,String>>listItems;
  9. privateListViewmListView;
  10. @Override
  11. protectedvoidonCreate(BundlesavedInstanceState){
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. listItems=newArrayList<Map<String,String>>();
  15. mListView=(ListView)findViewById(R.id.province_list);
  16. newNetAsyncTask().execute();
  17. //列表单击事件监听
  18. mListView.setOnItemClickListener(newAdapterView.OnItemClickListener(){
  19. @Override
  20. publicvoidonItemClick(AdapterView<?>parent,Viewview,
  21. intposition,longid){
  22. StringmCityName=listItems.get(position).get("city");
  23. StringcityName=getCityName(mCityName);
  24. Log.d("CityName",cityName);
  25. Intentintent=newIntent();
  26. //存储选择的城市名
  27. intent.putExtra("Cname",cityName);
  28. intent.setClass(CityActivity.this,WeatherActivity.class);
  29. startActivity(intent);
  30. }
  31. });
  32. }
  33. /**
  34. *拆分“城市(代码)”字符串,将“城市”字符串分离
  35. *@paramname
  36. *@return
  37. */
  38. publicStringgetCityName(Stringname){
  39. Stringcity="";
  40. intposition=name.indexOf('');
  41. city=name.substring(0,position);
  42. returncity;
  43. }
  44. classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
  45. @Override
  46. protectedvoidonPostExecute(Stringresult){
  47. if(result.equals("success")){
  48. //列表适配器
  49. SimpleAdaptersimpleAdapter=newSimpleAdapter(CityActivity.this,listItems,R.layout.province_item,
  50. newString[]{"city"},newint[]{R.id.province});
  51. mListView.setAdapter(simpleAdapter);
  52. }
  53. super.onPostExecute(result);
  54. }
  55. @Override
  56. protectedStringdoInBackground(Object...params){
  57. //根据命名空间和方法得到SoapObject对象
  58. SoapObjectsoapObject=newSoapObject(targetNameSpace,getSupportCity);
  59. //参数输入
  60. Stringname=getIntent().getExtras().getString("Pname");
  61. soapObject.addProperty("byProvinceName",name);
  62. //通过SOAP1.1协议得到envelop对象
  63. SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(
  64. SoapEnvelope.VER11);
  65. //将soapObject对象设置为envelop对象,传出消息
  66. envelop.dotNet=true;
  67. envelop.setOutputSoapObject(soapObject);
  68. HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
  69. //开始调用远程方法
  70. try{
  71. httpSE.call(targetNameSpace+getSupportCity,envelop);
  72. //得到远程方法返回的SOAP对象
  73. SoapObjectresultObj=(SoapObject)envelop.getResponse();
  74. //得到服务器传回的数据
  75. intcount=resultObj.getPropertyCount();
  76. for(inti=0;i<count;i++){
  77. Map<String,String>listItem=newHashMap<String,String>();
  78. listItem.put("city",resultObj.getProperty(i).toString());
  79. listItems.add(listItem);
  80. }
  81. }catch(IOExceptione){
  82. e.printStackTrace();
  83. return"IOException";
  84. }catch(XmlPullParserExceptione){
  85. e.printStackTrace();
  86. return"XmlPullParserException";
  87. }
  88. return"success";
  89. }
  90. }
  91. }


用于列表显示的xml重复使用,这里就不再重复写一次了,效果图,如图:

Android:WebService_第3张图片

最后,根据选择的城市或地区名称获得天气情况:

[java] view plain copy print ?
  1. publicclassWeatherActivityextendsActivity{
  2. //WSDL文档中的命名空间
  3. privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
  4. //WSDL文档中的URL
  5. privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
  6. //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
  7. privatestaticfinalStringgetWeatherbyCityName="getWeatherbyCityName";
  8. WeatherBeanmWBean;
  9. privateImageViewmImageView;
  10. privateEditTextmCityName;
  11. privateEditTextmTemp;
  12. privateEditTextmWeather;
  13. privateTextViewmToday;
  14. privateTextViewmDetail;
  15. privateintImage[];
  16. @Override
  17. protectedvoidonCreate(BundlesavedInstanceState){
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.weather);
  20. Image=newint[]{R.drawable.image0,R.drawable.image1,R.drawable.image2,
  21. R.drawable.image3,R.drawable.image4,R.drawable.image5,
  22. R.drawable.image6,R.drawable.image7,R.drawable.image8,
  23. R.drawable.image9,R.drawable.image10,R.drawable.image11,
  24. R.drawable.image12,R.drawable.image13,R.drawable.image14,
  25. R.drawable.image15,R.drawable.image16,R.drawable.image17,
  26. R.drawable.image18,R.drawable.image19,R.drawable.image20,
  27. R.drawable.image21,R.drawable.image22,R.drawable.image23,
  28. R.drawable.image24,R.drawable.image25,R.drawable.image26,
  29. R.drawable.image27};
  30. mWBean=newWeatherBean();
  31. mImageView=(ImageView)findViewById(R.id.picture);
  32. mCityName=(EditText)findViewById(R.id.city_name);
  33. mTemp=(EditText)findViewById(R.id.temp);
  34. mWeather=(EditText)findViewById(R.id.weather);
  35. mToday=(TextView)findViewById(R.id.today_weather);
  36. mDetail=(TextView)findViewById(R.id.city_detail);
  37. newNetAsyncTask().execute();
  38. }
  39. classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
  40. @Override
  41. protectedvoidonPostExecute(Stringresult){
  42. Stringimage=mWBean.getWeatherPicture();
  43. intposition=getImageId(image);
  44. Log.d("image",Image[position]+"");
  45. mImageView.setImageResource(Image[position]);
  46. mCityName.setText(mWBean.getCityName());
  47. mTemp.setText(mWBean.getTemp());
  48. mWeather.setText(mWBean.getWeather());
  49. mToday.setText(mWBean.getLiveWeather());
  50. mDetail.setText(mWBean.getCityDetail());
  51. super.onPostExecute(result);
  52. }
  53. publicintgetImageId(Stringpicture){
  54. intid=0;
  55. inttempId=picture.indexOf('.');
  56. Stringsub=picture.substring(0,tempId);
  57. id=Integer.parseInt(sub);
  58. returnid;
  59. }
  60. @Override
  61. protectedStringdoInBackground(Object...params){
  62. //根据命名空间和方法得到SoapObject对象
  63. SoapObjectsoapObject=newSoapObject(targetNameSpace,getWeatherbyCityName);
  64. Stringcity=getIntent().getExtras().getString("Cname");
  65. soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)
  66. //通过SOAP1.1协议得到envelop对象
  67. SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(SoapEnvelope.VER11);
  68. //将soapObject对象设置为envelop对象,传出消息
  69. envelop.dotNet=true;
  70. envelop.setOutputSoapObject(soapObject);
  71. //或者envelop.bodyOut=soapObject;
  72. HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
  73. //开始调用远程方法
  74. try{
  75. httpSE.call(targetNameSpace+getWeatherbyCityName,envelop);
  76. //得到远程方法返回的SOAP对象
  77. SoapObjectresultObj=(SoapObject)envelop.getResponse();
  78. //得到服务器传回的数据
  79. mWBean.setCityName(resultObj.getProperty(1).toString());
  80. mWBean.setTemp(resultObj.getProperty(5).toString());
  81. mWBean.setWeather(resultObj.getProperty(6).toString());
  82. mWBean.setWeatherPicture(resultObj.getProperty(8).toString());
  83. mWBean.setLiveWeather(resultObj.getProperty(10).toString());
  84. mWBean.setCityDetail(resultObj.getProperty(22).toString());
  85. }catch(IOExceptione){
  86. e.printStackTrace();
  87. return"IOException";
  88. }catch(XmlPullParserExceptione){
  89. e.printStackTrace();
  90. return"XmlPullParserException";
  91. }
  92. return"success";
  93. }
  94. }
  95. }


这里没有显示全部的信息,提供了一个存储部分天气信息的类:

[java] view plain copy print ?
  1. publicclassWeatherBean{
  2. privateStringCityName;
  3. privateStringTemp;
  4. privateStringWeather;
  5. privateStringWeatherPicture;
  6. privateStringLiveWeather;
  7. privateStringCityDetail;
  8. publicStringgetCityName(){
  9. returnCityName;
  10. }
  11. publicvoidsetCityName(StringcityName){
  12. CityName=cityName;
  13. }
  14. publicStringgetLiveWeather(){
  15. returnLiveWeather;
  16. }
  17. publicvoidsetLiveWeather(StringliveWeather){
  18. LiveWeather=liveWeather;
  19. }
  20. publicStringgetTemp(){
  21. returnTemp;
  22. }
  23. publicvoidsetTemp(Stringtemp){
  24. Temp=temp;
  25. }
  26. publicStringgetWeather(){
  27. returnWeather;
  28. }
  29. publicvoidsetWeather(Stringweather){
  30. Weather=weather;
  31. }
  32. publicStringgetWeatherPicture(){
  33. returnWeatherPicture;
  34. }
  35. publicvoidsetWeatherPicture(StringweatherPicture){
  36. WeatherPicture=weatherPicture;
  37. }
  38. publicStringgetCityDetail(){
  39. returnCityDetail;
  40. }
  41. publicvoidsetCityDetail(StringcityDetail){
  42. CityDetail=cityDetail;
  43. }
  44. }

显示天气状况的weather.xml文件:

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <LinearLayout
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:orientation="vertical">
  10. <TableLayout
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content">
  13. <TableRow>
  14. <TextView
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:text="天气实况:"
  18. android:textSize="16sp"/>
  19. <ImageView
  20. android:id="@+id/picture"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"/>
  23. </TableRow>
  24. <TableRow>
  25. <TextView
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:layout_weight="1"
  29. android:text="城市:"
  30. android:textSize="16sp"/>
  31. <EditText
  32. android:id="@+id/city_name"
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:layout_weight="2"
  36. android:hint="城市名称"
  37. android:editable="false"/>
  38. </TableRow>
  39. <TableRow>
  40. <TextView
  41. android:layout_width="wrap_content"
  42. android:layout_height="wrap_content"
  43. android:layout_weight="1"
  44. android:text="温度:"
  45. android:textSize="16sp"/>
  46. <EditText
  47. android:id="@+id/temp"
  48. android:layout_width="wrap_content"
  49. android:layout_height="wrap_content"
  50. android:layout_weight="2"
  51. android:hint="今日气温"
  52. android:editable="false"/>
  53. </TableRow>
  54. <TableRow>
  55. <TextView
  56. android:layout_width="wrap_content"
  57. android:layout_height="wrap_content"
  58. android:layout_weight="1"
  59. android:text="天气:"
  60. android:textSize="16sp"/>
  61. <EditText
  62. android:id="@+id/weather"
  63. android:layout_width="wrap_content"
  64. android:layout_height="wrap_content"
  65. android:layout_weight="2"
  66. android:hint="今日天气"
  67. android:editable="false"/>
  68. </TableRow>
  69. </TableLayout>
  70. <TextView
  71. android:id="@+id/today_weather"
  72. android:layout_width="fill_parent"
  73. android:layout_height="wrap_content"
  74. android:textSize="16sp"/>
  75. <TextView
  76. android:layout_width="fill_parent"
  77. android:layout_height="wrap_content"
  78. android:text="城市简介:"
  79. android:textSize="16sp"/>
  80. <TextView
  81. android:id="@+id/city_detail"
  82. android:layout_width="fill_parent"
  83. android:layout_height="wrap_content"
  84. android:textSize="16sp"/>
  85. </LinearLayout>
  86. </ScrollView>


效果图如图:

Android:WebService_第4张图片

这里许多功能做得不是很完善,大家可以根据自己的需要进行设计~

更多相关文章

  1. eclipse:打开 eclipse 出现 “android sdk content loader 0%”
  2. Android Service的使用方法 音乐播放器实例
  3. Android定制RadioButton样式三种实现方法
  4. android调用Webservice方法
  5. Android 文件读写操作方法总结
  6. 对android里布局文件当中的TextView对象设置事件监听,但是不响应
  7. 低版本android project在高版本ADK中运行方法
  8. Android中应用界面主题Theme使用方法和页面定时跳转应用

随机推荐

  1. Android中App内部切换语言包
  2. Android(安卓)WIFI 列表重复项问题
  3. Android复习之旅--Intent
  4. Android(安卓)开发最佳实践--转自Git
  5. android 多层目录文件创建
  6. android在线预览office
  7. Tablayout+Viewpager+Fragment组合使用以
  8. React Native获取移动设备信息(react-nat
  9. Android(安卓)基于源码的科学计算器——C
  10. Android(安卓)studio 2.2 JNI ffmpeg 简