在Android中调用WebService【附源码】


某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查。我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数据费时费电;二是流量贵如金那。我个人比较推荐的做法是使用Java或PHP等开发接口或者编写WebService进行数据库的增删该查,然后Android调用接口或者WebService进行数据的交互。本文就给大家讲解在Android中如何调用远程服务器端提供的WebService。

免费下载地址在 http://linux.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /2012年资料/3月/10日/在Android中调用WebService【附源码】/

 

既然是调用WebService,我们首先的搭建WebService服务器。为了便于操作,我们就使用网上免费的WebService进行学习。

地址:http://www.webxml.com.cn/zh_cn/index.aspx

下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地

调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。

首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:

mobilesoap.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  
  3.   <soap12:Body>  
  4.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
  5.       <mobileCode>$mobile</mobileCode>  
  6.       <userID></userID>  
  7.     </getMobileCodeInfo>  
  8.   </soap12:Body>  
  9. </soap12:Envelope>

其次,设计MainActivity布局文件,
main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="手机号码" />  
  11.     <EditText  
  12.         android:id="@+id/mobileNum"   
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:text=""  
  16.         />  
  17.     <Button  
  18.         android:id="@+id/btnSearch"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="查询"  
  22.         />  
  23.     <TextView  
  24.         android:id="@+id/mobileAddress"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         />  
  28. </LinearLayout>
  • 1
  • 2
  • 下一页

相关内容