MIDP 規範要求所有裝置必須支援 HTTP 協定,Socket 則為選項。本文說明如何使用 javax.microedition.io.Connector 開發 HTTP 聯網應用。
void postViaHttpConnection(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
try {
c = (HttpConnection) Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-US");
os = c.openOutputStream();
os.write("LIST games\n".getBytes());
os.flush();
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();
String type = c.getType();
processType(type);
int len = (int) c.getLength();
if (len > 0) {
byte[] data = new byte[len];
int actual = 0, bytesread = 0;
while (bytesread != len && actual != -1) {
actual = is.read(data, bytesread, len - bytesread);
bytesread += actual;
}
process(data);
} else {
int ch;
while ((ch = is.read()) != -1) {
process((byte) ch);
}
}
} catch (ClassCastException e) {
throw new IllegalArgumentException("Not an HTTP URL");
} finally {
if (is != null) is.close();
if (os != null) os.close();
if (c != null) c.close();
}
}
手機 → 無線網路 → 營運商 WAP Gateway → Web Server (CGI/ASP/JSP/Servlet) → 回傳相同路徑。WAP Gateway 對開發者透明,無需特別處理。
writeUTF()、writeInt()、writeBoolean(),Server 端必須對應 readUTF()、readInt()、readBoolean(),順序與型別需完全一致。DataInputStream/DataOutputStream 處理二進位資料更方便。