在行動裝置呼叫 Web Service,kSOAP 是最輕量、成熟的選擇。本文以簡單「字串轉大寫」服務為例,示範伺服器端發布 (Axis) 與 J2ME 客戶端呼叫完整流程。
package com.jagie.J2ME.ws;
public class StringProcessor {
public String process(String name) {
return name.toUpperCase();
}
}
jagiews/ (Web App 根目錄) ├── WEB-INF/ │ ├── web.xml │ ├── server-config.wsdd │ ├── classes/ │ │ └── com/jagie/J2ME/ws/StringProcessor.class │ └── lib/ │ ├── axis.jar, axis-ant.jar, commons-discovery.jar │ ├── commons-logging.jar, jaxrpc.jar, log4j-1.2.8.jar │ ├── saaj.jar, wsdl4j.jar
server-config.wsdd:定義服務 StringProcess,允許方法 process,類別 com.jagie.J2ME.ws.StringProcessor。
web.xml:配置 AxisServlet 對應 /services/*,AdminServlet、SOAPMonitorService 等。
jagiews 發布為 Web Application (如 WebLogic: https://localhost:7001/jagiews)https://localhost:7001/jagiews/services/StringProcess?method=process&name=qqQQQQQQ 即成功package com.jagie.J2ME.ws;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class WSClientMIDlet extends MIDlet {
static WSClientMIDlet instance;
public WSClientMIDlet() { instance = this; }
public void startApp() {
Display.getDisplay(this).setCurrent(new DisplayForm());
}
public void pauseApp() {}
public void destroyApp(boolean u) {}
public static void quitApp() {
instance.destroyApp(true); instance.notifyDestroyed(); instance = null;
}
}
package com.jagie.J2ME.ws;
import javax.microedition.lcdui.*;
public class DisplayForm extends Form implements CommandListener, Runnable {
private TextField textField1;
private Thread t;
public DisplayForm() {
super("字串轉換 WebService 測試");
textField1 = new TextField("待處理字串:", "", 15, TextField.ANY);
append(textField1);
addCommand(new Command("Exit", Command.EXIT, 1));
addCommand(new Command("Process", Command.OK, 1));
setCommandListener(this);
}
public void commandAction(Command cmd, Displayable d) {
if (cmd.getCommandType() == Command.EXIT) WSClientMIDlet.quitApp();
else if (cmd.getCommandType() == Command.OK) { t = new Thread(this); t.start(); }
}
public void run() {
String input = textField1.getString();
String result = new StringProcessorStub().process(input);
append(new StringItem("處理結果:", result));
}
}
package com.jagie.J2ME.ws;
import org.ksoap.*;
import org.ksoap.transport.HttpTransport;
public class StringProcessorStub {
public String process(String name) {
String result = null;
try {
// 建立 SOAP 物件:命名空間 + 方法名
SoapObject rpc = new SoapObject(
"https://localhost:7001/jagiews/services/StringProcess", "process");
rpc.addProperty("name", name); // 參數
// HTTP 傳輸層
HttpTransport ht = new HttpTransport(
"https://localhost:7001/jagiews/services/StringProcess", "");
// 同步呼叫並取得回傳值
result = (String) ht.call(rpc);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
SoapObject 封裝請求,HttpTransport.call() 同步取得回應。run() 中執行),否則 commandAction 阻塞會凍結畫面。server-config.wsdd 與 web.xml,Jar 包齊全。localhost 替換為真實伺服器 IP/域名。有了 kSOAP,J2ME 整合企業級 Web Service 近在咫尺。