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

Android 通過 ksoap2 調用 WebService 的完整實作

編輯:Android 資訊

一、WebService 是什麼

WebService 基於 SOAP 協定實現主機與主機之間的通信。由於 SOAP 以 XML 傳送資料,具備平台無關性,因此成為解決異構系統整合的重要方案,例如讓 Java 平台與 .NET 平台互通。正因如此,它在 Web 應用中佔有舉足輕重的地位——許多機構都在各自平台上對外發布了 WebService,例如天氣預報、航班資訊、股市行情等,讓任何平台的客戶端都能取用(當然部分服務是付費的)。

二、ksoap2-android 組件

Android 端調用 WebService 有兩條路。一是自己寫:透過 HttpURLConnection 建立連線,手動做 I/O 讀寫收發資料,再自行解析 XML,過程繁瑣且容易出錯。二是使用第三方組件,最常見的就是 ksoap2-android。

ksoap2-android 是一個開源組件,針對 Android 平台提供了輕量高效的 SOAP 類庫,能讓 Android 端與 WebService 之間的通信變得相當省事。

1. 環境準備

專案位址:https://code.google.com/p/ksoap2-android/,下載最新版 jar 並加入專案即可。本文使用的是 ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar。

2. 使用步驟

(1)準備 Web 服務參數

// webservice 服務位址
String url = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
// web 服務的命名空間
String namespace = "https://WebXml.com.cn/";
// 請求服務的方法名稱
String methodName = "getMobileCodeInfo";
// soap 請求位址
String soapActionAddress = "https://WebXml.com.cn/getMobileCodeInfo";

(2)建立 HttpTransportSE,負責送出請求

HttpTransportSE transport = new HttpTransportSE(url);

(3)建立 SoapObject 並加入要傳送的資料

SoapObject soapObject = new SoapObject(namespace, methodName);
soapObject.addProperty(name, value);   // 加入資料
// ...

(4)建立 SoapSerializationEnvelope,指定 XML 版本與 request body

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = soapObject;
envelope.setOutputSoapObject(soapObject);

(5)送出請求,調用 WebService 方法

httpTransportSE.call(soapActionAddress, envelope);
// 服務傳回的資訊會放在 envelope 的 bodyIn 屬性中

(6)取得回傳資料

SoapObject object = (SoapObject) envelope.bodyIn;

三、實作案例:查詢手機號碼歸屬地

運行效果如下:

完整程式碼:

public class MainActivity extends Activity {

    // 手機歸屬地 Webservice 的參數資訊
    private static final String nameSpaceAddress  = "https://WebXml.com.cn/";
    private static final String urlAddress        = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
    private static final String methodNameAddress = "getMobileCodeInfo";
    private static final String soapActionAddress = "https://WebXml.com.cn/getMobileCodeInfo";

    private TextView telAddress = null;
    private EditText tel = null;
    private Button btnAddress = null;
    private String txtAddress = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAddress  = (Button) this.findViewById(R.id.btnSearchAddress);
        telAddress  = (TextView) this.findViewById(R.id.telAddress);
        tel         = (EditText) this.findViewById(R.id.telNo);

        btnAddress.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 網路請求必須放在子執行緒
                new Thread(new Runnable() {
                    public void run() {
                        getTelAddress();
                    }
                }).start();
            }
        });
    }

    /** 請求 WebService 並取得手機號碼歸屬地 */
    public void getTelAddress() {
        SoapObject soapObject = new SoapObject(nameSpaceAddress, methodNameAddress);

        // 這些屬性會透過 SOAP 協定傳送給伺服器
        soapObject.addProperty("mobileCode", tel.getText().toString());
        soapObject.addProperty("userId", "");

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        envelope.dotNet = true;                     // 服務端是 .NET 平台時需要設為 true
        envelope.setOutputSoapObject(soapObject);

        HttpTransportSE httpTransportSE = new HttpTransportSE(urlAddress);
        try {
            httpTransportSE.call(soapActionAddress, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 取得回傳資料
        SoapObject object = (SoapObject) envelope.bodyIn;
        txtAddress = object.getProperty(0).toString();

        // 通知主執行緒更新 UI
        handlerAddress.sendEmptyMessage(0);
    }

    Handler handlerAddress = new Handler() {
        public void handleMessage(Message msg) {
            telAddress.setText(txtAddress);
            Toast.makeText(MainActivity.this,
                    "獲取號碼歸屬地成功" + txtAddress, Toast.LENGTH_LONG).show();
        }
    };
}

這裡有兩個實務上很容易忽略的細節:一是網路請求一定要放在子執行緒,否則在較新版本的 Android 上會直接拋出 NetworkOnMainThreadException;二是 envelope.dotNet = true 這行,只有當服務端是 .NET 平台時才需要設定,漏掉它可能導致回傳的資料結構解析不出來。

四、附錄:常見的公開 WebService 位址

手機歸屬地服務
https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

天氣預報 Web 服務(資料來源:中國氣象局)
https://www.webxml.com.cn/WebServices/WeatherWebService.asmx

IP 位址查詢
https://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx

中英雙向翻譯 Web 服務
https://www.webxml.com.cn/WebServices/TranslatorWebService.asmx

火車時刻表
https://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx

航班查詢服務
https://webservice.webxml.com.cn/webservices/DomesticAirline.asmx

中國股票行情資料 Web 服務
https://www.webxml.com.cn/WebServices/ChinaStockWebService.asmx

中國電視節目預告
https://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx

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