編輯:關於 Android 程式設計
Android 要與後端的 Java Web Service 溝通,最常見的組合就是 ksoap2 搭配 Apache CXF。本文以一個可運行的完整範例,示範如何建立 CXF 服務端、如何正確引入 ksoap2 套件,以及在客戶端完成「傳入並回傳字串」與「取回複合格物件」兩種呼叫情境。
官方下載頁為 https://code.google.com/p/ksoap2-android/,點擊下載連結即可取得 jar 檔。本文採用 ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar,這個版本已經把相依套件全部打包進去,不必再另外補齊。
由於重點放在 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);
// 集合必須先被封裝成物件,才能在 Web Service 中傳遞
StudentList studentList = new StudentList();
studentList.setStuList(stuList);
return studentList;
}
}
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;
}
}
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
新建專案後,把 ksoap2 的 jar 匯入。這裡有個很容易踩到的地雷:
不要用「專案右鍵 → Build Path → Add External Archives…」的方式匯入。這種做法表面上看似成功,實際上執行時仍會拋出 ClassNotFoundException 或 NoClassDefFoundError:
正確做法和開發 Web 專案一樣:在專案根目錄下建立 libs 資料夾,把 jar 直接複製進去,IDE 會自動幫你加入建置路徑。
這樣一來類別就能正常參照,不會再出現找不到類別的錯誤。
HttpTransportSE 物件,負責實際的傳輸與呼叫:HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);SoapSerializationEnvelope 物件:SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);SoapObject 請求物件,需傳入命名空間與方法名稱:SoapObject request = new SoapObject(SERVICE_NS, methodName);addProperty(String name, Object value) 加入:request.addProperty("name", "1006010054");envelope.bodyOut = request;ht.call(null, envelope);envelope.bodyIn 取出 SoapObject 並解析,即為回傳值:SoapObject result = (SoapObject) envelope.bodyIn;String name = result.getProperty(0).toString();
<?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>
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();
}
}
}
別忘了註冊 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 攤開來看括號的嵌套關係,就能很快判斷要剝幾層。
Android 仿微信照片選擇器實現預覽查看圖片
下面進入正題,先來看看實現效果: 整體實現思路如下: 先到手機中掃描 jpeg 與 png 圖片。 獲取圖片的路徑,以及圖片所在的父路徑名(也就是文件夾名)。
微信怎麼掃描二維碼?電腦版登入教學
微信電腦版通常需要透過手機掃描二維碼登入。以下以電腦版登入為例說明。1. 開啟電腦版微信,畫面會顯示二維碼。2. 手機開啟微信,進入「發現」>「掃一掃」。3. 掃描電腦畫
Android 監聽軟鍵盤彈出與隱藏的兩種實現方案
情境描述:版面檔中有一個 ScrollView,內含一個 EditView,版面底部還有一個控制項。程式一啟動時 EditView 就獲取焦點、彈出軟鍵盤,把底部的控制項
新浪微博 OAuth2.0 授權與 SDK 實戰(Android 篇)
一、微博開發者平台的使用這一節主要介紹如何使用新浪微博的開發者平台。如果你想做一個基於微博登錄或其他一系列操作的應用,首先要到他們的官網註冊成為開發者:https://o