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

J2ME 設備實現 HTTP 協議:GCF 架構、GET/POST 請求與 MIDlet 完整代碼

     編輯:Java 相關知識

背景:無線設備上的網絡編程

J2SE 提供 100+ 網絡類,但手機/PDA 資源受限。J2ME 定義子集 javax.microedition.io,**通用連接框架 (GCF)** 統一抽象:

  • 頂層介面 Connection + 6 子介面(CLDC 必備)。
  • 廠商自行實作具體協議(Socket、Datagram、HTTP 等)。
  • MIDP **強制實作 HttpConnection**(繼承 ContentConnection),成為無線網絡開發基石。

發送 HTTP GET 請求

public String sendHttpGet(String url) throws IOException {
    HttpConnection hcon = null;
    DataInputStream dis = null;
    StringBuffer msg = new StringBuffer();
    try {
        hcon = (HttpConnection) Connector.open(url); // 預設 GET
        dis = new DataInputStream(hcon.openInputStream());
        int ch;
        while ((ch = dis.read()) != -1) {
            msg.append((char) ch);
        }
    } finally {
        if (hcon != null) hcon.close();
        if (dis != null) dis.close();
    }
    return msg.toString();
}

發送 HTTP POST 請求

public String sendHttpPost(String url) throws IOException {
    HttpConnection hcon = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuffer msg = new StringBuffer();
    String requestBody = "This is a POST.";
    try {
        hcon = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
        hcon.setRequestMethod(HttpConnection.POST);
        dos = hcon.openDataOutputStream();
        byte[] data = requestBody.getBytes();
        for (int i = 0; i < data.length; i++) dos.writeByte(data[i]);
        // dos.flush() 在某些手機會導致 Transfer-Encoding: chunked 產生亂碼,建議省略
        dis = new DataInputStream(hcon.openInputStream()); // 打開輸入流自動刷新
        int ch;
        while ((ch = dis.read()) != -1) msg.append((char) ch);
    } finally {
        if (hcon != null) hcon.close();
        if (dis != null) dis.close();
        if (dos != null) dos.close();
    }
    return msg.toString();
}

完整 MIDlet 代碼結構

  • HttpMidlet extends MIDlet implements CommandListener
  • UI:Form(輸入 URL)、List(選 GET/POST)、Form(顯示回應)
  • 命令:SEND、EXIT、BACK
  • commandAction 分發:選 GET → sendHttpGet,選 POST → sendHttpPost
  • 資源釋放:destroyApp 清空所有 UI 元件引用

關鍵避坑提醒

  1. Connector.open(url) 預設 READ_ONLY,POST 必須 Connector.READ_WRITE。
  2. HttpConnection.POST 常數需顯式設定。
  3. dos.flush() 可能觸發分塊編碼導致伺服器解析異常,**建議移除**,靠 openInputStream() 隱式刷新。
  4. 所有流與連接必須在 finally 關閉,防止記憶體洩漏。

展望

HTTP 是 MIDP 唯一強制協議,隨無線設備普及,掌握 GCF + HttpConnection 將成為移動開發核心競爭力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved