本文內容與 ID 78170 高度相似,均出自同一來源。此處提供補充視角:更完善的異常處理、執行緒模式、連線釋放順序,並修正原文中 flush() 可能導致的 Transfer-Encoding: chunked 問題。
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) {}
}
}
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) {}
}
}
StringBuffer.append 高效,且便於指定 UTF-8 解碼。flush():防止某些手機產生 chunked 編碼錯誤。finally 中各自 try-catch,確保所有資源釋放。new Thread(() -> {
try {
String resp = httpPost(url, "param=value");
// UI 更新需在事件執行緒:Display.callSerially(() -> ...)
} catch (IOException e) { /* 處理網路錯誤 */ }
}).start();
掌握這些細節,能讓 J2ME 網絡通訊更穩健、相容性更好。實際專案中建議封裝成 HttpClient 工具類,統一處理編碼、超時、重試、Cookie 等橫切關注點。