首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

J2ME 網路應用開發實戰:HTTP 連線、MVC 架構與執行緒模式完整指南

     編輯:J2ME

J2ME 網路基礎

MIDP 強制支援 HTTP,Socket 為選擇性。核心類別在 javax.microedition.io,關鍵為 Connector.open(url) 回傳 Connection 介面,轉型為 HttpConnection 使用。

HTTP POST 完整流程範例

void postViaHttpConnection(String url) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        c = (HttpConnection) Connector.open(url);
        c.setRequestMethod(HttpConnection.POST);
        c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
        c.setRequestProperty("Content-Type", "application/octet-stream");
        
        os = c.openOutputStream();
        os.write("LIST games\n".getBytes());
        os.flush();
        
        int rc = c.getResponseCode(); // 觸發實際連線與傳送
        if (rc != HttpConnection.HTTP_OK) 
            throw new IOException("HTTP response: " + rc);
        
        is = c.openInputStream();
        String type = c.getType();
        int len = (int) c.getLength();
        
        if (len > 0) {
            byte[] data = new byte[len];
            int read = 0, actual;
            while (read < len && (actual = is.read(data, read, len - read)) != -1)
                read += actual;
            process(data);
        } else {
            int ch;
            while ((ch = is.read()) != -1) process((byte) ch);
        }
    } finally {
        if (is != null) is.close();
        if (os != null) os.close();
        if (c != null) c.close();
    }
}

關鍵實務原則

  1. 必須使用獨立執行緒:網路操作阻塞主執行緒會凍結 UI,甚至被系統終止。提供等待動畫提升體驗。
  2. 採用 MVC 模式:介面多時,分離 Model(資料/邏輯)、View(Canvas/Form)、Controller(事件分發) 利於維護。
  3. 資料協定設計:推薦 POST + DataOutputStream/DataInputStream。發送端 writeUTF()/writeInt(),接收端對應 readUTF()/readInt(),順序必須一致。
  4. 錯誤處理:檢查回應碼、捕獲 IOException、ClassCastException,確保資源釋放。

完整專案架構範例

Servlet 伺服器端

public class MyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        DataInputStream dis = new DataInputStream(req.getInputStream());
        String msg = dis.readUTF();
        DataOutputStream dos = new DataOutputStream(resp.getOutputStream());
        dos.writeUTF(msg + "haha");
        dis.close(); dos.close();
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException { doPost(req, resp); }
}

用戶端核心類別

  • HttpCommMIDlet:啟動 UIController
  • UIController:管理畫面切換、事件分發(EventHandler 執行緒)
  • InputCanvas:輸入介面,CommandListener 觸發連線事件
  • DisplayCanvas:顯示伺服器回應
  • HttpCommHandler:封裝 HTTP 連線、發送/接收、資源關閉邏輯

程式碼關鍵片段:HttpCommHandler

public class HttpCommHandler {
    private String url;
    public HttpCommHandler(String url) { this.url = url; }
    
    public String sendMessage(String msg) throws IOException {
        HttpConnection conn = null;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            conn = openConnection();
            out = new DataOutputStream(conn.openOutputStream());
            out.writeUTF(msg);
            out.flush();
            
            in = new DataInputStream(conn.openDataInputStream());
            return in.readUTF();
        } finally {
            closeQuietly(conn, in, out);
        }
    }
    
    private HttpConnection openConnection() throws IOException {
        HttpConnection c = (HttpConnection) Connector.open(url);
        c.setRequestMethod(HttpConnection.POST);
        c.setRequestProperty("Content-Type", "application/octet-stream");
        c.setRequestProperty("User-Agent", System.getProperty("microedition.profiles"));
        return c;
    }
    // closeQuietly 略
}

部署建議

  • 伺服器建議 Tomcat + Servlet/JSP
  • 用戶端測試真機需注意 GPRS 費用與穩定性
  • 生產環境應加入重試機制、逾時設定、憑證驗證(HTTPS)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved