Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

安卓開發調用遠端 WebService:手機號碼歸屬地查詢完整實作

編輯:Android 開發實例

需要跟 MySQL、Oracle 這類資料庫打交道時,很多朋友的第一反應是在 Android 端直接載入 JDBC 驅動,然後做增刪改查。這個做法我不建議:一方面手機的運算與電力都遠不如電腦,處理大量資料既慢又耗電;另一方面行動網路流量可是要錢的。比較合理的架構是用 Java、PHP 等後端技術寫好介面或 WebService,把資料庫操作留在伺服器端,Android 只負責呼叫。

本文就以「手機號碼歸屬地查詢」這個公開的 WebService 為例,示範 Android 如何呼叫遠端服務。流程不複雜:發出請求、取得回應、解析後顯示。

第一步:準備 SOAP 請求範本

把請求訊息存成一個 XML 檔,參數位置先用 $ 佔位,執行時再動態替換。這樣做的好處是請求結構與程式碼分離,之後要改欄位不必動 Java 邏輯。

mobilesoap.xml

<?xml version="1.0" encoding="utf-8"?>

<soap12:Envelope xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap12="https://www.w3.org/2003/05/soap-envelope">

<soap12:Body>

<getMobileCodeInfo xmlns="https://WebXml.com.cn/">

<mobileCode>$mobile</mobileCode>

<userID></userID>

</getMobileCodeInfo>

</soap12:Body>

</soap12:Envelope>

第二步:寫版面配置

main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="https://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="手機號碼" />

<EditText

android:id="@+id/mobileNum"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text=""

/>

<Button

android:id="@+id/btnSearch"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="查詢"

/>

<TextView

android:id="@+id/mobileAddress"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

/>

</LinearLayout>

第三步:撰寫 MainActivity

package com.szy.webservice;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.util.Xml;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends Activity

{

private EditText mobileNum;

private TextView mobileAddress;

private static final String TAG = "MainActivity";

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mobileNum = (EditText) this.findViewById(R.id.mobileNum);

mobileAddress = (TextView) this.findViewById(R.id.mobileAddress);

Button btnSearch = (Button) this.findViewById(R.id.btnSearch);

btnSearch.setOnClickListener(new View.OnClickListener()

{

@Override

public void onClick(View v)

{

// 獲取電話號碼

String mobile = mobileNum.getText().toString();

// 讀取xml文件

InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");

try

{

// 顯示電話號碼地理位置,該段代碼不合理,僅供參考

mobileAddress.setText(getMobileAddress(inStream, mobile));

} catch (Exception e)

{

Log.e(TAG, e.toString());

Toast.makeText(MainActivity.this, "查詢失敗", 1).show();

}

}

});

}

/**

* 獲取電話號碼地理位置

*

* @param inStream

* @param mobile

* @return

* @throws Exception

*/

private String getMobileAddress(InputStream inStream, String mobile) throws Exception

{

// 替換xml文件中的電話號碼

String soap = readSoapFile(inStream, mobile);

byte[] data = soap.getBytes();

// 提交Post請求

URL url = new URL("https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

conn.setConnectTimeout(5 * 1000);

conn.setDoOutput(true);

conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");

conn.setRequestProperty("Content-Length", String.valueOf(data.length));

OutputStream outStream = conn.getOutputStream();

outStream.write(data);

outStream.flush();

outStream.close();

if (conn.getResponseCode() == 200)

{

// 解析返回信息

return parseResponseXML(conn.getInputStream());

}

return "Error";

}

private String readSoapFile(InputStream inStream, String mobile) throws Exception

{

// 從流中獲取文件信息

byte[] data = readInputStream(inStream);

String soapxml = new String(data);

// 占位符參數

Map<String, String> params = new HashMap<String, String>();

params.put("mobile", mobile);

// 替換文件中占位符

return replace(soapxml, params);

}

/**

* 讀取流信息

*/

private byte[] readInputStream(InputStream inputStream) throws Exception

{

byte[] buffer = new byte[1024];

int len = -1;

ByteArrayOutputStream outSteam = new ByteArrayOutputStream();

while ((len = inputStream.read(buffer)) != -1)

{

outSteam.write(buffer, 0, len);

}

outSteam.close();

inputStream.close();

return outSteam.toByteArray();

}

/**

* 替換文件中占位符

*/

private String replace(String xml, Map<String, String> params) throws Exception

{

String result = xml;

if (params != null && !params.isEmpty())

{

for (Map.Entry<String, String> entry : params.entrySet())

{

String name = "\$" + entry.getKey();

Pattern pattern = Pattern.compile(name);

Matcher matcher = pattern.matcher(result);

if (matcher.find())

{

result = matcher.replaceAll(entry.getValue());

}

}

}

return result;

}

/**

* 解析XML文件

*/

private static String parseResponseXML(InputStream inStream) throws Exception

{

XmlPullParser parser = Xml.newPullParser();

parser.setInput(inStream, "UTF-8");

int eventType = parser.getEventType();// 產生第一個事件

while (eventType != XmlPullParser.END_DOCUMENT)

{

// 只要不是文檔結束事件

switch (eventType)

{

case XmlPullParser.START_TAG:

String name = parser.getName();// 獲取解析器當前指向的元素的名稱

if ("getMobileCodeInfoResult".equals(name))

{

return parser.nextText();

}

break;

}

eventType = parser.next();

}

return null;

}

}

別忘了權限

需要連網,記得在 AndroidManifest.xml 加上:

<uses-permission android:name="android.permission.INTERNET"/>

整段邏輯拆開來看其實很樸素:readSoapFile() 讀範本並用正則把 $mobile 換成真實號碼,getMobileAddress() 用 HttpURLConnection 以 POST 送出 SOAP 信封,parseResponseXML() 再用 XmlPullParser 把 getMobileCodeInfoResult 節點的文字取出來。

這裡要特別提醒一個實務問題:範例把網路請求直接寫在按鈕的 onClick 裡,在較新的 Android 版本上會因為主執行緒禁止網路操作而直接拋出 NetworkOnMainThreadException。正式專案請把 getMobileAddress() 這段搬到 AsyncTask、Thread 或任何背景執行緒中,再透過 Handler 回寫 UI。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved