歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 在Android中調用WebService【附源碼】

在Android中調用WebService【附源碼】

日期:2017/3/1 10:27:07   编辑:Linux編程

某些情況下我們可能需要與Mysql或者Oracle數據庫進行數據交互,有些朋友的第一反應就是直接在Android中加載驅動然後進行數據的增刪改查。我個人不推薦這種做法,一是手機畢竟不是電腦,操作大量數據費時費電;二是流量貴如金那。我個人比較推薦的做法是使用Java或PHP等開發接口或者編寫WebService進行數據庫的增刪該查,然後Android調用接口或者WebService進行數據的交互。本文就給大家講解在Android中如何調用遠程服務器端提供的WebService。

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.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>
Copyright © Linux教程網 All Rights Reserved