Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 透過 ksoap2 呼叫 CXF Web Service 完整實作教學

編輯:關於 Android 程式設計

前言

Android 要與後端的 Java Web Service 溝通,最常見的組合就是 ksoap2 搭配 Apache CXF。本文以一個可運行的完整範例,示範如何建立 CXF 服務端、如何正確引入 ksoap2 套件,以及在客戶端完成「傳入並回傳字串」與「取回複合格物件」兩種呼叫情境。

一、準備 ksoap2-android 套件

官方下載頁為 https://code.google.com/p/ksoap2-android/,點擊下載連結即可取得 jar 檔。本文採用 ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar,這個版本已經把相依套件全部打包進去,不必再另外補齊。

二、建立 Java 服務端(CXF)

由於重點放在 Android 客戶端,這裡直接給出服務端程式碼。

2.1 服務介面

介面宣告兩個方法:一個收送簡單字串,另一個回傳「自訂物件 + 集合」。

package xidian.sl.service.webService;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import xidian.sl.service.impl.webService.StudentList;

@WebService
@SOAPBinding(style = Style.RPC)
public interface TestService {
    public String getUser(@WebParam(name = "name") String name);
    public StudentList getStuList();
}

2.2 介面實作

package xidian.sl.service.impl.webService;

import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import xidian.sl.entity.Students;
import xidian.sl.service.webService.TestService;

@WebService(endpointInterface = "xidian.sl.service.webService.TestService")
public class TestServiceImpl implements TestService {

    @Override
    public String getUser(String name) {
        System.out.println("客戶端傳遞的名字為 = " + name);
        return name;
    }

    @Override
    public StudentList getStuList() {
        System.out.println("該方法被調用");
        List<Students> stuList = new ArrayList<Students>();

        Students stu1 = new Students();
        stu1.setStuName("沈浪");
        stu1.setStuNum("1006010054");
        stu1.setStuSex("男");
        stuList.add(stu1);

        Students stu2 = new Students();
        stu2.setStuName("香香");
        stu2.setStuNum("1006010043");
        stu2.setStuSex("女");
        stuList.add(stu2);

        // 集合必須先被封裝成物件,才能在 Web Service 中傳遞
        StudentList studentList = new StudentList();
        studentList.setStuList(stuList);
        return studentList;
    }
}

2.3 集合的包裝物件

package xidian.sl.service.impl.webService;

import java.util.List;
import xidian.sl.entity.Students;

public class StudentList {
    private List<Students> stuList;

    public List<Students> getStuList() {
        return stuList;
    }

    public void setStuList(List<Students> stuList) {
        this.stuList = stuList;
    }
}

2.4 Spring 設定檔

web.xml 中的 CXFServlet 設定完成後,Spring 組態檔只需再補上以下內容即可:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="https://cxf.apache.org/jaxws"
    xsi:schemaLocation="
        https://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        https://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        https://cxf.apache.org/jaxws
        https://cxf.apache.org/schemas/jaxws.xsd">

    <!-- 這幾個 xml 位於 cxf-2.5.0.jar 的 META-INF 目錄下 -->
    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <!-- cxf-extension-soap.xml 已標示為廢棄,不再匯入 -->
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- id:Spring bean 的識別名稱
         implementor:實際的實作類別
         address:該 Web Service 的相對位址 -->
    <bean id="testServiceImpl"
        class="xidian.sl.service.impl.webService.TestServiceImpl" />

    <jaxws:endpoint id="testService"
        implementor="#testServiceImpl"
        address="/test" />
</beans>

其中 /test 來自 address 屬性,services 則是 web.xml 中 CXFServlet 的映射路徑。

三、驗證服務端

啟動 Tomcat 後,在瀏覽器輸入下列網址,若能看到 WSDL 描述檔,代表服務已成功發布:

https://localhost:8090/WebExam/services/test?wsdl

四、建立 Android 客戶端

新建專案後,把 ksoap2 的 jar 匯入。這裡有個很容易踩到的地雷:

不要用「專案右鍵 → Build Path → Add External Archives…」的方式匯入。這種做法表面上看似成功,實際上執行時仍會拋出 ClassNotFoundException 或 NoClassDefFoundError:

正確做法和開發 Web 專案一樣:在專案根目錄下建立 libs 資料夾,把 jar 直接複製進去,IDE 會自動幫你加入建置路徑。

這樣一來類別就能正常參照,不會再出現找不到類別的錯誤。

五、ksoap2 呼叫的七個標準步驟

  1. 建立 HttpTransportSE 物件,負責實際的傳輸與呼叫:
    HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
  2. 建立 SoapSerializationEnvelope 物件:
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  3. 建立 SoapObject 請求物件,需傳入命名空間與方法名稱:
    SoapObject request = new SoapObject(SERVICE_NS, methodName);
  4. 若有參數,呼叫 addProperty(String name, Object value) 加入:
    request.addProperty("name", "1006010054");
    注意:這裡的參數名稱不必與服務端一致,只要順序對應即可。
  5. 把請求物件設為外送的 SOAP 本文:
    envelope.bodyOut = request;
  6. 呼叫遠端方法:
    ht.call(null, envelope);
  7. 從 envelope.bodyIn 取出 SoapObject 並解析,即為回傳值:
    SoapObject result = (SoapObject) envelope.bodyIn;
    String name = result.getProperty(0).toString();

六、實例一:呼叫回傳字串的方法

版面配置 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />
</LinearLayout>

Activity 程式碼

package xidian.sl.android.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class WebServiceSimpleDemo extends Activity {
    final static String SERVICE_NS = "https://webService.service.sl.xidian/";
    final static String SERVICE_URL = "https://192.168.1.103:8090/WebExam/services/test";

    private EditText txt1;
    private EditText txt2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt1 = (EditText) findViewById(R.id.editText1);
        txt2 = (EditText) findViewById(R.id.editText2);

        String methodName = "getUser";
        HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
        ht.debug = true;

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        SoapObject request = new SoapObject(SERVICE_NS, methodName);
        request.addProperty("name", "1006010054");
        envelope.bodyOut = request;

        try {
            ht.call(null, envelope);
            if (envelope.getResponse() != null) {
                txt2.setText("有返回");
                SoapObject result = (SoapObject) envelope.bodyIn;
                String name = result.getProperty(0).toString();
                txt1.setText("返回值 = " + name);
            } else {
                txt2.setText("無返回");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

別忘了註冊 Activity,並加上網路權限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="xidian.sl.android.webservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WebServiceSimpleDemo"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <!-- 對外網路存取權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

七、實例二:呼叫回傳複合物件的方法

與前例相比,差別只在於回傳值的解析方式:需要用多層 getProperty() 依序剝開外層包裝、集合,再取出每個學生物件。

package xidian.sl.android.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class WebServiceComplexDemo extends Activity {
    final static String SERVICE_NS = "https://webService.service.sl.xidian/";
    final static String SERVICE_URL = "https://192.168.1.103:8090/WebExam/services/test";

    private EditText txt1;
    private EditText txt2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt1 = (EditText) findViewById(R.id.editText1);
        txt2 = (EditText) findViewById(R.id.editText2);

        String methodName = "getStuList";
        HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
        ht.debug = true;

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        SoapObject request = new SoapObject(SERVICE_NS, methodName);
        envelope.bodyOut = request;

        try {
            ht.call(null, envelope);
            txt2.setText("回傳的值 :" + envelope.getResponse());

            if (envelope.getResponse() != null) {
                SoapObject result = (SoapObject) envelope.bodyIn;
                // 第一層:StudentList 包裝物件
                SoapObject soapChilds = (SoapObject) result.getProperty(0);
                StringBuffer sb = new StringBuffer();
                // 第二層:逐一取出每個 Students
                for (int i = 0; i < soapChilds.getPropertyCount(); i++) {
                    SoapObject stu = (SoapObject) soapChilds.getProperty(i);
                    sb.append("姓名[" + i + "] = " + stu.getProperty(0).toString() + "\n");
                    sb.append("學號[" + i + "] = " + stu.getProperty(1).toString() + "\n");
                    sb.append("性別[" + i + "] = " + stu.getProperty(2).toString() + "\n\n");
                }
                txt1.setText(sb.toString());
            } else {
                txt1.setText("無返回");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

關鍵在於看懂回傳值的階層結構:每多一層包裝就多呼叫一次 getProperty()。把實際回傳的 XML 攤開來看括號的嵌套關係,就能很快判斷要剝幾層。

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