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

Android 呼叫 Web Service(CXF)實戰詳解:ksoap2 用戶端

編輯:Android 開發實例

Google 為 Android 平台開發 Web Service 提供了支援,提供了 Ksoap2-android 相關套件。

一、下載 ksoap2-android

可以直接到 https://code.google.com/p/ksoap2-android/ 下載,點擊下載連結即可。我使用的是 ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar。

二、建立 Java 服務端

由於重點在 Android 用戶端,服務端就直接給程式碼。先定義介面(提供一個傳字串、一個傳複合物件+集合的方法):

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();
}

實作類別:

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);
//將List集合封裝成一個對象才能在webService中進行傳遞
StudentList studentList = new StudentList();
studentList.setStuList(stuList);
return studentList;
}
}

集合的封裝物件(List 需包裝成物件才能在 Web Service 中傳遞):

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;
}
}

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">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!-- 這裡配置服務接口 -->
<bean id="testServiceImpl" class="xidian.sl.service.impl.webService.TestServiceImpl" >
</bean>
<jaxws:endpoint id="testService"
implementor="#testServiceImpl"
address="/test" />
</beans>

啟動 Tomcat 後,於瀏覽器輸入 https://localhost:8090/WebExam/services/test?wsdl 即可查看 WSDL:

三、建立 Android 用戶端

新建專案後匯入 ksoap2 的 jar。這裡要特別注意:匯入方式不要用「build path → add external archives」,因為那樣表面上匯入了,實際上仍無法引用,啟動時會一直報錯:

正確做法和開發 Web 一樣,在專案下新建 lib 或 libs 資料夾,把 jar 直接複製進去,IDE 會自動幫你引入:

這樣就不會再報類別無法引用的錯誤了。

呼叫步驟

(1)建立 HttpTransportSE 物件,用於呼叫 Web Service 操作: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 設定。注意:參數名不一定要與服務端相同,只要順序對應即可。request.addProperty("name", "1006010054");

(5)將 SoapObject 設為 envelope 的 bodyOut:envelope.bodyOut = request;

(6)呼叫 call() 執行遠端 Web Service:ht.call(null, envelope);

(7)完成後存取 bodyIn 屬性並解析,即可取得回傳值:SoapObject result = (SoapObject) envelope.bodyIn;

完整範例

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 並加上網路權限 android.permission.INTERNET,執行後即可看到結果:

接著試著呼叫回傳複合物件的方法,差別在於回傳值的處理,要用幾層 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;
SoapObject soapChilds = (SoapObject)result.getProperty(0);
StringBuffer sb = new StringBuffer();
for(int i=0; i <soapChilds.getPropertyCount(); i++){
SoapObject soapChildsChilds = (SoapObject)soapChilds.getProperty(i);
sb.append("姓名["+i+"] = "+soapChildsChilds.getProperty(0).toString()+"\n");
sb.append("學號["+i+"] = "+soapChildsChilds.getProperty(1).toString()+"\n");
sb.append("性別["+i+"] = "+soapChildsChilds.getProperty(2).toString()+"\n"+"\n");
}
txt1.setText(sb.toString());
}else{
txt1.setText("無返回");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}

關鍵在於看懂回傳值的層次結構,對照括號的嵌套關係來決定要呼叫幾次 getProperty(),就能正確取出每一筆資料。

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