Android调用webservice

本文介绍如何在Android应用中使用ksoap2库调用WebService,实现查询天气和手机号码归属地的功能。文章涵盖控件使用、线程处理、UI更新及错误处理等方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 前言:一晃距离上次搭android环境已经4个月了,还没怎么学习android,买的android书看了遍目录,看了最基本的控件以及都能实现哪些功能(而且只是看看,没练),androidbus上100多天的签到记录(只是为了下载东西时不缺下载分的未雨绸缪),仅此而已。当初想玩android时,只是为了实现一个小小的需求,通过手机关闭电脑(每次睡前看会手机,但手机连着电脑开启的共享wifi,玩完手机还得起来关电脑,真麻烦,当时也未找到遥控关机的相关app)。周五发现360出了软件版的wifi,下了个360wifi,发现这款360wifi配合其app竟然有遥控关机这个功能,看来这种需求的人不少。自己等自己的这个软件等到花都谢了,当时想着通过android调用WCF服务,然后WCF服务里实现关机的逻辑。周五晚上临时决定周末搞定android调用Webservice,经过周五周六两晚加周六一天,初步完成,过程是艰辛的,特此记录。

        例子准备工作:

        a.ksoap2的下载, 下载地址 ,刚看了看最新的版本是3.3.0,我例子中用的2.5.4版本的;
        b.搜索免费的webservice,我用的是 webxml 上的,选了天气和手机归属地作为示例;

        例子中的关键技术:

        a.基本的控件以及布局
           涉及ScrollView、TableLayout、Button、TextView、EditText的用法。其中EditText有个hint属性,可以在为空时显示提示信息,另外注意的是,在最新的版本中xmlns只需要一次声明否则会报诸如“Unexpected namespace prefix "xmlns" found for tag LinearLayout”的错,此例中只在ScrollView声明了一次。
        b.ksoap2调用webservice
            首先从webservice上获得一些必要的信息,包括NameSpace、SoapAction、url,url就是webservice的url,然后在浏览器中打开webservice,点开方法,如下图所示找出NameSpace、SoapAction


           调用webservice的一般步骤如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. SoapObject soapObject = new SoapObject(nameSpaceWeather, methodWeather);  
  2. //给调用参数赋值  
  3. soapObject.addProperty("theCityCode""1960");        
  4. soapObject.addProperty("userId""");  
  5. //设置一些基本参数  
  6. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  7.                 SoapEnvelope.VER11);  
  8. envelope.bodyOut = soapObject;  
  9. envelope.dotNet = true;       
  10. envelope.setOutputSoapObject(soapObject);  
  11. HttpTransportSE httpTransportSE = new HttpTransportSE(urlWeather);  
  12. try{  
  13.     //实际调用webservice的操作  
  14.     httpTransportSE.call(soapActionWeather, envelope);  
  15. }   
  16. catch (Exception e){  
  17.     e.printStackTrace();  
  18. }  
  19. //获得调用的结果  
  20. SoapObject object = (SoapObject) envelope.bodyIn;  
  21. txtWeather = object.getProperty(0).toString();  

        c.线程知识
           android 4.0之后的版本不可以在主线程中进行网络操作,故要调用webservice需要新开线程;

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void onClick(View v) {  
  2.     new Thread(new Runnable() {  
  3.         public void run() {  
  4.             //这边是具体的操作  
  5.         }  
  6.     }).start();  
  7. }  

        d.跨线程修改更新UI数据;
           android禁止跨线程修改ui,如果线程是在oncreate中创建则子线程中可以直接修改ui,但如果在按钮的事件中新建的子线程执行更新ui则会出现异常;本例子是在按钮的事件中新建的子线程,解决方案就是在子线程执行完之后将更新ui的操作交给主线程;先定义如下

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Handler handlerWeather = new Handler() {  
  2.     public void handleMessage(Message msg) {  
  3.         //这边是更新UI的操作  
  4.         weather.setText(txtWeather);  
  5.     }  
  6. };  
           然后在子线程中要更新ui的地方执行handlerWeather.sendEmptyMessage(0);这样就将更新ui的操作交给主线程了;

        e.弹框提示以及日志记录;

           执行某个操作之后如果有个提示,那就更好了,比如网络操作如果没提示,到底是执行完了没结果还是没执行或者报错了,有提示那就一目了然了。本示例中采用浮出提示,然后自动消失。代码:

[java]  view plain copy
  1. Toast.makeText(MainActivity.this"获取天气成功", Toast.LENGTH_LONG).show();  

          日志记录有助于调试,方便找出异常的地点以及原因。本示例采用:

[java]  view plain copy
  1. System.out.println("××0××更新号码归属地数据,归属地为:"+txtAddress);  

          然后在LogCat中查看,下图是我运行的日志截图:

        搭建例子完整过程及代码

        a.新建android项目

        本例最低版本设置的是4.1(因为最新的编译器当最低版本低于4.1时会自动增加一个诸如appcompat_v7_2兼容包,删掉就会出错,看着怪不舒服的,故最低选用的4.1),将下载下来的ksoap2包在解决方案上复制到libs中,然后右键解决方案-->Build Path-->Add External Archives…,选择libs下的那个ksoap2包。开始我没有在解决方案中复制到libs,直接添加的,然后写代码时一直报找不到包的错误。

        b.项目的整体布局如下:

        c.页面设计代码activity_main.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ScrollView  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:id="@+id/myscroll"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7. <TableLayout  
  8.     android:orientation="vertical"  
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11.     android:paddingTop="5dip"  
  12.     android:paddingLeft="5dip"  
  13.     android:paddingRight="5dip">  
  14.       <TableRow>  
  15.         <Button android:id="@+id/btnSearchWeather"  
  16.             android:layout_width="fill_parent"  
  17.             android:layout_height="wrap_content"  
  18.             android:text="查询如皋天气"/>     
  19.      </TableRow>   
  20.       <TableRow>  
  21.           <TextView  
  22.                 android:layout_width="fill_parent"   
  23.                 android:layout_height="wrap_content"   
  24.                 android:text="可查询江苏省如皋市的天气预报"/>                
  25.     </TableRow>   
  26.     <TableRow>       
  27.         <TextView android:id="@+id/weatherInfo"  
  28.             android:layout_width="wrap_content"  
  29.             android:layout_height="wrap_content"/>              
  30.     </TableRow>     
  31.     <TableRow>  
  32.         <EditText android:id="@+id/telNo"  
  33.             android:layout_width="fill_parent"  
  34.             android:layout_height="wrap_content"  
  35.             android:hint="请输入手机号"/>  
  36.     </TableRow>  
  37.      <TableRow>  
  38.         <Button android:id="@+id/btnSearchAddress"  
  39.             android:layout_width="fill_parent"  
  40.             android:layout_height="wrap_content"  
  41.             android:layout_gravity="right"  
  42.             android:text="查询归属地"/>  
  43.         </TableRow>   
  44.     <TableRow>  
  45.         <TextView android:id="@+id/telAddress"  
  46.             android:layout_width="fill_parent"   
  47.             android:layout_height="wrap_content"/>  
  48.     </TableRow>  
  49.       
  50. </TableLayout>  
  51. </ScrollView>   

        d.后台代码MainActivity.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.webservice0517;  
  2.   
  3. import org.ksoap2.SoapEnvelope;  
  4. import org.ksoap2.serialization.SoapObject;  
  5. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  6. import org.ksoap2.transport.HttpTransportSE;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.TextView;  
  16. import android.widget.Toast;  
  17.   
  18. public class MainActivity extends Activity {  
  19.     ///天气Webservice的参数信息  
  20.     static final String nameSpaceWeather = "http://WebXml.com.cn/";  
  21.     static final String urlWeather   
  22.             = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";  
  23.     static final String methodWeather = "getWeather";  
  24.     static final String soapActionWeather = "http://WebXml.com.cn/getWeather";  
  25.     ///手机归属地Webservice的参数信息  
  26.     static final String nameSpaceAddress = "http://WebXml.com.cn/";  
  27.     static final String urlAddress   
  28.             = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";  
  29.     static final String methodNameAddress = "getMobileCodeInfo";  
  30.     static final String soapActionAddress   
  31.             = "http://WebXml.com.cn/getMobileCodeInfo";  
  32.   
  33.     private Button btnWeather = null;  
  34.     private Button btnAddress = null;  
  35.     private EditText tel = null;  
  36.     private TextView weather = null;  
  37.     private TextView telAddress = null;  
  38.   
  39.     private String txtWeather = "";  
  40.     private String txtAddress = "";  
  41.   
  42.     Handler handlerWeather = new Handler() {  
  43.         public void handleMessage(Message msg) {  
  44.             System.out.println("××0××更新天气数据,天气为:"+txtWeather);  
  45.             weather.setText(txtWeather);  
  46.             Toast.makeText(MainActivity.this"获取天气成功", Toast.LENGTH_LONG)  
  47.                     .show();  
  48.         }  
  49.     };  
  50.     Handler handlerAddress = new Handler() {  
  51.         public void handleMessage(Message msg) {  
  52.             System.out.println("××0××更新号码归属地数据,归属地为:"+txtAddress);  
  53.             telAddress.setText(txtAddress);  
  54.             Toast.makeText(MainActivity.this"获取号码归属地成功"+txtAddress, Toast.LENGTH_LONG)  
  55.                     .show();  
  56.         }  
  57.     };  
  58.   
  59.     @Override  
  60.     protected void onCreate(Bundle savedInstanceState) {  
  61.         super.onCreate(savedInstanceState);  
  62.         setContentView(R.layout.activity_main);  
  63.         btnWeather = (Button) this.findViewById(R.id.btnSearchWeather);  
  64.         btnAddress = (Button) this.findViewById(R.id.btnSearchAddress);  
  65.         weather = (TextView) this.findViewById(R.id.weatherInfo);  
  66.         telAddress = (TextView) this.findViewById(R.id.telAddress);  
  67.         tel = (EditText) this.findViewById(R.id.telNo);  
  68.   
  69.         btnAddress.setOnClickListener(new Button.OnClickListener() {  
  70.             @Override  
  71.             public void onClick(View v) {  
  72.                 new Thread(new Runnable() {  
  73.                     public void run() {  
  74.                         getTelAddress();  
  75.                     }  
  76.                 }).start();  
  77.   
  78.             }  
  79.         });  
  80.           
  81.         btnWeather.setOnClickListener(new Button.OnClickListener() {  
  82.             @Override  
  83.             public void onClick(View v) {  
  84.                 new Thread(new Runnable() {  
  85.                     public void run() {  
  86.                         getWeather();  
  87.                     }  
  88.                 }).start();  
  89.   
  90.             }  
  91.         });  
  92.     }  
  93.     public void getWeather()   
  94.     {  
  95.         System.out.println("××1××进入getWeather方法");  
  96.         SoapObject soapObject = new SoapObject(nameSpaceWeather, methodWeather);  
  97.         ///这边1960是江苏如皋的地区码,这个也是通过这个webservice的方法查的  
  98.         soapObject.addProperty("theCityCode""1960");  
  99.         ///免费用户userid为空  
  100.         soapObject.addProperty("userId""");         
  101.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  102.                 SoapEnvelope.VER11);  
  103.         envelope.bodyOut = soapObject;  
  104.         envelope.dotNet = true;       
  105.         envelope.setOutputSoapObject(soapObject);  
  106.         HttpTransportSE httpTransportSE = new HttpTransportSE(urlWeather);  
  107.         System.out.println("××2××基本服务设置完毕,下面开始调用服务");  
  108.         try   
  109.         {  
  110.             httpTransportSE.call(soapActionWeather, envelope);  
  111.             System.out.println("××3××调用webservice服务成功");  
  112.         }   
  113.         catch (Exception e)   
  114.         {  
  115.             e.printStackTrace();  
  116.             System.out.println("××4××调用webservice服务失败");  
  117.         }  
  118.   
  119.         SoapObject object = (SoapObject) envelope.bodyIn;  
  120.         System.out.println("××5××获得服务数据成功");  
  121.         txtWeather = object.getProperty(0).toString();  
  122.         System.out.println("××6××解析服务数据成功,数据为:"+txtWeather);  
  123.         System.out.println("××7××向主线程发送消息,显示天气信息");  
  124.         handlerWeather.sendEmptyMessage(0);  
  125.         System.out.println("××8××向主线程发送消息成功,getWeather函数执行完毕");  
  126.     }  
  127.     public void getTelAddress()   
  128.     {  
  129.         System.out.println("××1××进入getTelAddress方法");  
  130.         SoapObject soapObject   
  131.                 = new SoapObject(nameSpaceAddress, methodNameAddress);    
  132.         ///这边理论上要做输入验证的,例子图省事没做输入验证验证  
  133.         soapObject.addProperty("mobileCode", tel.getText().toString());  
  134.         soapObject.addProperty("userId""");         
  135.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  136.                 SoapEnvelope.VER11);  
  137.         envelope.bodyOut = soapObject;  
  138.         envelope.dotNet = true;       
  139.         envelope.setOutputSoapObject(soapObject);  
  140.         HttpTransportSE httpTransportSE = new HttpTransportSE(urlAddress);  
  141.         System.out.println("××2××基本服务设置完毕,下面开始调用服务");  
  142.         try   
  143.         {  
  144.             httpTransportSE.call(soapActionAddress, envelope);  
  145.             System.out.println("××3××调用webservice服务成功");  
  146.         }   
  147.         catch (Exception e)   
  148.         {  
  149.             e.printStackTrace();  
  150.             System.out.println("××4××调用webservice服务失败");  
  151.         }  
  152.   
  153.         SoapObject object = (SoapObject) envelope.bodyIn;  
  154.         System.out.println("××5××获得服务数据成功");  
  155.         txtAddress = object.getProperty(0).toString();  
  156.         System.out.println("××6××解析服务数据成功,数据为:"+txtAddress);  
  157.         System.out.println("××7××向主线程发送消息,显示号码归属地");  
  158.         handlerAddress.sendEmptyMessage(0);  
  159.         System.out.println("××8××向主线程发送消息成功,getTelAddress函数执行完毕");  
  160.     }  
  161. }  
       e.增加访问网络的权限

           AndroidManifest.xml中加权限:<uses-permission android:name="android.permission.INTERNET" />

        f.运行的截图:




        后记:

        在写例子进度缓慢主要的两个原因:
        a..android版本的升级变化导致很多前人原有的代码以及书的示例代码不能直接运行;

        b..本人对android了解太少了,没实际写过android的代码,整个过程犯的最傻的一个问题是Button控件写成ButtonView(没有动手实际写过代码,与Button是继承自TextView混了);

        写例子时还碰到的问题以及一些其他建议:

        a.页面上有六个TableRow,为了布局更合理,我把下面的三个移到上面,然后就一直报加载失败,没法在模拟器上运行,报错截图如下:


           详细报错报的cast button失败,没找到原因,关闭再开,重启电脑都没效果,再恢复到下面就一切正常了,不知道为什么,不知是不是TableRow的什么设置没设置好还是环境有问题。
        b.几个非常有用的快捷键
        Ctrl+/可以快速提示;
        Ctrl+Shift+F可以快速格式化代码;

        Ctrl+Shift+O自动导入所缺的包;
        Ctrl+M可以切换标准模式和全代码模式;
        调整代码的大小,环境默认的大小是10,太小了,看的眼睛都累,注释也看不清,窗口点击鼠标右键选择最后一个preference(偏好)-->General-->Appearance在右边选择Java-->Java Editor Text Font-->Edit--选择14这样java代码字体变大了,xml的还没变,xml的跟上面设置类似在Basic-->Text Editor Block Selection Font里设置;

        页面布局变化,没法复原成原有的布局,可以点击Windows-->Reset Perspective重新复原。

        例子写完感觉也还很简单,对自己是一个记录,希望也能对读者有些帮助,欢迎阅读、讨论、转载,转载请保留原文链接

        源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值