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

J2ME 通用聯網框架開發 HTTP 應用程式實作

     編輯:J2ME

MIDP 規範要求所有裝置必須支援 HTTP 協定,Socket 則為選項。本文說明如何使用 javax.microedition.io.Connector 開發 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-Language", "en-US");
        
        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 code: " + rc);
        }
        
        is = c.openInputStream();
        String type = c.getType();
        processType(type);
        
        int len = (int) c.getLength();
        if (len > 0) {
            byte[] data = new byte[len];
            int actual = 0, bytesread = 0;
            while (bytesread != len && actual != -1) {
                actual = is.read(data, bytesread, len - bytesread);
                bytesread += actual;
            }
            process(data);
        } else {
            int ch;
            while ((ch = is.read()) != -1) {
                process((byte) ch);
            }
        }
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("Not an HTTP URL");
    } finally {
        if (is != null) is.close();
        if (os != null) os.close();
        if (c != null) c.close();
    }
}

聯網架構運作原理

手機 → 無線網路 → 營運商 WAP Gateway → Web Server (CGI/ASP/JSP/Servlet) → 回傳相同路徑。WAP Gateway 對開發者透明,無需特別處理。

關鍵開發原則

  1. 必須使用獨立執行緒:網路操作不可在主執行緒(事件派發執行緒)執行,否則會阻塞 UI。建議顯示等待動畫提升使用者體驗。
  2. 採用 MVC 模式管理多畫面導航:聯網應用畫面較多,Model-View-Controller 分離可提升維護性。
  3. 資料傳輸協定一致性:Client 端 writeUTF()、writeInt()、writeBoolean(),Server 端必須對應 readUTF()、readInt()、readBoolean(),順序與型別需完全一致。
  4. 推薦使用 POST 方法:比 GET 更靈活,配合 DataInputStream/DataOutputStream 處理二進位資料更方便。

標準聯網流程

  1. 建立連線、設定請求方法(POST)、設定 Header
  2. 開啟輸出串流、傳送資料
  3. 檢查回應狀態碼、錯誤處理、讀取回應資料
  4. 關閉連線與串流
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved