J2SE 提供 100+ 網絡類,但手機/PDA 資源受限。J2ME 定義子集 javax.microedition.io,**通用連接框架 (GCF)** 統一抽象:
Connection + 6 子介面(CLDC 必備)。HttpConnection**(繼承 ContentConnection),成為無線網絡開發基石。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();
}
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();
}
HttpMidlet extends MIDlet implements CommandListenerForm(輸入 URL)、List(選 GET/POST)、Form(顯示回應)commandAction 分發:選 GET → sendHttpGet,選 POST → sendHttpPostdestroyApp 清空所有 UI 元件引用Connector.open(url) 預設 READ_ONLY,POST 必須 Connector.READ_WRITE。HttpConnection.POST 常數需顯式設定。dos.flush() 可能觸發分塊編碼導致伺服器解析異常,**建議移除**,靠 openInputStream() 隱式刷新。finally 關閉,防止記憶體洩漏。HTTP 是 MIDP 唯一強制協議,隨無線設備普及,掌握 GCF + HttpConnection 將成為移動開發核心競爭力。