構建移動互聯網應用的基礎是客戶端與服務端的可靠通信。本文提供一個完整的 用戶登錄交互示例,服務端基於 J2EE Servlet,客戶端基於 J2ME MIDP 2.0,通過 HTTP POST 交換數據,涵蓋 Servlet 異步響應、MIDlet 多線程網絡請求、表單數據編解碼、異常處理等工程化細節,可直接用於項目原型開發。
HttpServlet,處理 doPost(doGet 轉發)。username、password。zdw/admin)。ByteArrayOutputStream + DataOutputStream 構建二進制響應體:writeUTF("true") 或 "false"。Content-Type: application/octet-stream,Content-Length,狀態碼 200。public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
if ("zdw".equals(username) && "admin".equals(password)) {
dos.writeUTF("true");
} else {
dos.writeUTF("false");
}
byte[] data = baos.toByteArray();
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("application/octet-stream");
resp.setContentLength(data.length);
OutputStream os = resp.getOutputStream();
os.write(data);
os.close();
}
}
MIDlet 實現 CommandListener。Form、兩個 TextField(用戶名、密碼掩碼)、Command(登錄、退出)、Alert(成功/失敗提示)。commandAction 處理命令:退出銷毀 MIDlet;登錄啟動獨立線程執行網絡請求(避免阻塞事件線程導致死鎖)。inTurnServer() 核心流程:public void inTurnServer() {
try {
String url = "https://localhost:8888/LoginWeb/LoginServlet";
HttpConnection conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.setRequestProperty("Connection", "close");
String formData = "username=" + username.getString() + "&password=" + password.getString();
byte[] data = formData.getBytes();
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream os = conn.openOutputStream();
os.write(data);
os.close();
int rc = conn.getResponseCode();
if (rc == HttpConnection.HTTP_OK) {
DataInputStream dis = new DataInputStream(conn.openInputStream());
String result = dis.readUTF();
dis.close();
if ("true".equals(result)) initAlertOK();
else {
initAlertError();
username.delete(0, username.getString().length());
password.delete(0, password.getString().length());
}
}
} catch (IOException e) { e.printStackTrace(); }
}
| 要點 | 說明 |
|---|---|
| 線程隔離 | MIDlet 事件線程不可執行阻塞 I/O,必須 new Thread(...).start() |
| 數據編碼 | 表單數據 application/x-www-form-urlencoded,響應 DataOutputStream.writeUTF / DataInputStream.readUTF 統一編碼 |
| 連接關閉 | 請求頭 Connection: close,用完即關閉,避免連接洩漏 |
| 異常處理 | 捕獲 IOException 打印堆棧,生產環境需友好提示用戶 |
| 部署要求 | MyEclipse 項目 + WTK 模擬器 + Tomcat 服務器 |