MIDP 強制支援 HTTP,Socket 為選擇性。核心類別在 javax.microedition.io,關鍵為 Connector.open(url) 回傳 Connection 介面,轉型為 HttpConnection 使用。
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-Type", "application/octet-stream");
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: " + rc);
is = c.openInputStream();
String type = c.getType();
int len = (int) c.getLength();
if (len > 0) {
byte[] data = new byte[len];
int read = 0, actual;
while (read < len && (actual = is.read(data, read, len - read)) != -1)
read += actual;
process(data);
} else {
int ch;
while ((ch = is.read()) != -1) process((byte) ch);
}
} finally {
if (is != null) is.close();
if (os != null) os.close();
if (c != null) c.close();
}
}
writeUTF()/writeInt(),接收端對應 readUTF()/readInt(),順序必須一致。IOException、ClassCastException,確保資源釋放。public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DataInputStream dis = new DataInputStream(req.getInputStream());
String msg = dis.readUTF();
DataOutputStream dos = new DataOutputStream(resp.getOutputStream());
dos.writeUTF(msg + "haha");
dis.close(); dos.close();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { doPost(req, resp); }
}
UIControllerEventHandler 執行緒)CommandListener 觸發連線事件public class HttpCommHandler {
private String url;
public HttpCommHandler(String url) { this.url = url; }
public String sendMessage(String msg) throws IOException {
HttpConnection conn = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
conn = openConnection();
out = new DataOutputStream(conn.openOutputStream());
out.writeUTF(msg);
out.flush();
in = new DataInputStream(conn.openDataInputStream());
return in.readUTF();
} finally {
closeQuietly(conn, in, out);
}
}
private HttpConnection openConnection() throws IOException {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("Content-Type", "application/octet-stream");
c.setRequestProperty("User-Agent", System.getProperty("microedition.profiles"));
return c;
}
// closeQuietly 略
}