javax.microedition.io.Connector — 唯一入口點,open() 回傳 Connection 介面void postViaHttpConnection(String url) throws IOException {
HttpConnection conn = null;
InputStream is = null;
OutputStream os = null;
try {
// 1. 建立連線
conn = (HttpConnection) Connector.open(url);
// 2. 設定請求屬性
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Language", "en-US");
// 3. 發送資料
os = conn.openOutputStream();
String postData = "action=list&category=games";
os.write(postData.getBytes("UTF-8"));
os.flush();
// 4. 檢查回應碼
int rc = conn.getResponseCode(); // 此處才真正建立連線發送請求
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP Error: " + rc);
}
// 5. 處理回應
String contentType = conn.getType();
processContentType(contentType);
long len = conn.getLength();
is = conn.openInputStream();
if (len > 0) {
byte[] data = new byte[(int) len];
int read = 0, total = 0;
while (total < len && (read = is.read(data, total, (int) len - total)) != -1) {
total += read;
}
processData(data);
} else {
// Chunked 或未知長度
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) bos.write(ch);
processData(bos.toByteArray());
}
} catch (ClassCastException e) {
throw new IllegalArgumentException("Non-HTTP URL: " + url);
} finally {
// 6. 關閉資源(依序關閉)
if (is != null) try { is.close(); } catch (IOException ignore) {}
if (os != null) try { os.close(); } catch (IOException ignore) {}
if (conn != null) try { conn.close(); } catch (IOException ignore) {}
}
}
手機應用 → 無線網路 → 營運商 WAP Gateway → Internet → Web Server (Servlet/JSP/PHP/ASP.NET)
↑ ↓
└──────────── 透明轉發(開發者無需關心) ────────────┘
WAP Gateway 負責無線協定(WTP/WTLS)與 HTTP 協定轉換,對開發者完全透明。
網路操作會阻塞,絕不可在主執行緒(事件派發執行緒)執行。否則 UI 凍結、甚至被看門狗終止。
new Thread(() -> {
try { postViaHttpConnection(url); }
catch (IOException e) { showError(e); }
}).start();
聯網時顯示「載入中」動畫提升使用者體驗。
| 方式 | 優點 | 缺點 | 建議場景 |
|---|---|---|---|
| GET + URL Encoding | 簡單、可快取 | 長度限制、資料暴露 | 簡單查詢、靜態資源 |
| POST + application/x-www-form-urlencoded | 標準、支援較大資料 | 效率一般 | 表單提交、一般 API |
| POST + DataOutputStream/DataInputStream | 二進位、高效能、型別安全 | 需雙端協定一致 | 高頻交換、遊戲同步 |
| POST + JSON/XML | 跨平台、可讀、工具豐富 | 解析耗資源 | 複雜結構資料、Web Service 整合 |
關鍵:發送端 writeUTF() → 接收端 readUTF(),順序與型別必須完全對應。
Connector.open()、設定方法、HeaderopenOutputStream()、寫入、flush()getResponseCode()、錯誤碼分流處理openInputStream()、讀取資料、依序關閉所有流與連線ConnectionTimeout、實作重試機制getBytes("UTF-8")