Generic Connection Framework (GCF) 是 J2ME CLDC 規範定義的核心網路 API。因行動裝置資源受限,標準 java.net、java.io 套件不適用,GCF 以介面導向設計、工廠模式建立連線、標準 URL 簡化開發,成為行動裝置聯網的基石。
CLDC 1.1 定義 8 個介面、Connector 工廠類別與 ConnectionNotFoundException。MIDP 2.0 擴充 HTTP/HTTPS、Socket、Datagram 等介面,賦予 MIDlet 完整通訊能力。
Connection:根介面,僅定義 close()。StreamConnection / DatagramConnection:對應串流與資料報傳輸。InputConnection、OutputConnection:提供 openInputStream()、openOutputStream()。HttpConnection:繼承 ContentConnection,為 MIDP 必須支援的高階協定。
所有連線透過 Connector.open(String url) 取得,URL 格式遵循 RFC 2396:{scheme}:[{target}][{parms}]。
String url = "https://myhost:8080/servlet";
HttpConnection conn = (HttpConnection) Connector.open(url);
try {
// 1. 開啟連線與串流
InputStream in = conn.openInputStream();
// 2. 資料收發邏輯...
} catch (IOException e) {
// 錯誤處理
} finally {
// 3. 必須關閉連線釋放資源
try { if (conn != null) conn.close(); } catch (IOException ignored) {}
}
掌握 GCF 介面階層、URL 格式與連線關閉流程,是開發健壯 J2ME 網路應用的前提。後續文章將詳細示範 HTTP、Socket、SMS 等具體協定的資料傳輸實作。