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

在無線 J2ME 設備上實現 HTTP 傳輸:GET/POST 請求與最佳實踐 (補充版)

     編輯:J2ME

本文與 ID 78170 關係

本文內容與 ID 78170 高度相似,均出自同一來源。此處提供補充視角:更完善的異常處理、執行緒模式、連線釋放順序,並修正原文中 flush() 可能導致的 Transfer-Encoding: chunked 問題。

改良版 HTTP GET 方法

public String httpGet(String url) throws IOException {
    HttpConnection conn = null;
    InputStream is = null;
    try {
        conn = (HttpConnection) Connector.open(url);
        conn.setRequestMethod(HttpConnection.GET);
        is = conn.openInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        int len;
        while ((len = is.read(buf)) != -1) baos.write(buf, 0, len);
        return new String(baos.toByteArray(), "UTF-8");
    } finally {
        if (is != null) try { is.close(); } catch (Exception ignored) {}
        if (conn != null) try { conn.close(); } catch (Exception ignored) {}
    }
}

改良版 HTTP POST 方法

public String httpPost(String url, String body) throws IOException {
    HttpConnection conn = null;
    OutputStream os = null;
    InputStream is = null;
    try {
        conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
        conn.setRequestMethod(HttpConnection.POST);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length));
        os = conn.openOutputStream();
        os.write(body.getBytes("UTF-8"));
        // 不要 os.flush()!
        is = conn.openInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        int len;
        while ((len = is.read(buf)) != -1) baos.write(buf, 0, len);
        return new String(baos.toByteArray(), "UTF-8");
    } finally {
        if (os != null) try { os.close(); } catch (Exception ignored) {}
        if (is != null) try { is.close(); } catch (Exception ignored) {}
        if (conn != null) try { conn.close(); } catch (Exception ignored) {}
    }
}

關鍵改進點總結

  1. ByteArrayOutputStream 累積回應:比逐字元 StringBuffer.append 高效,且便於指定 UTF-8 解碼。
  2. 明確關閉順序:OutputStream → InputStream → Connection,避免資源洩漏。
  3. 移除 flush():防止某些手機產生 chunked 編碼錯誤。
  4. 設定 Content-Length:利於伺服器解析,避免 411 錯誤。
  5. 異常安全關閉:finally 中各自 try-catch,確保所有資源釋放。

執行緒調用模板

new Thread(() -> {
    try {
        String resp = httpPost(url, "param=value");
        // UI 更新需在事件執行緒:Display.callSerially(() -> ...)
    } catch (IOException e) { /* 處理網路錯誤 */ }
}).start();

結語

掌握這些細節,能讓 J2ME 網絡通訊更穩健、相容性更好。實際專案中建議封裝成 HttpClient 工具類,統一處理編碼、超時、重試、Cookie 等橫切關注點。

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