MIDP 建立在 CLDC 的 Generic Connection Framework 之上,強制支援 HTTP。所有連線均由 Connector.open(url) 建立,回傳對應介面實例。HTTP 連線可設定請求方法、Header,並開啟 I/O 串流。
HttpConnection conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream os = conn.openOutputStream();
InputStream is = conn.openInputStream();
<%! String name; %>
<%
name = request.getParameter("name");
java.util.Date today = new java.util.Date();
out.println("Got: " + name);
out.println("Date&time: " + today);
%>
public class InvokeJSPMidlet extends MIDlet implements CommandListener {
private Display display;
private TextField nameField;
private Form form;
private String url = "https://127.0.0.1:8080/examples/jsp/today.jsp";
private Command callCmd = new Command("Query", Command.OK, 1);
private Command clearCmd = new Command("Clear", Command.STOP, 1);
private String myName;
public InvokeJSPMidlet() {
display = Display.getDisplay(this);
nameField = new TextField("Name:", "", 25, TextField.ANY);
form = new Form("Invoke JSP");
form.append(nameField);
form.addCommand(callCmd);
form.addCommand(clearCmd);
form.setCommandListener(this);
}
public void startApp() { display.setCurrent(form); }
public void pauseApp() {}
public void destroyApp(boolean u) { notifyDestroyed(); }
void invokeJSP(String url) throws IOException {
HttpConnection c = null; InputStream is = null; OutputStream os = null;
StringBuffer buf = new StringBuffer();
TextBox resultBox = null;
try {
c = (HttpConnection) Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
os = c.openOutputStream();
os.write(("name=" + myName).getBytes());
os.flush();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
buf.append((char) ch);
}
resultBox = new TextBox("Response", buf.toString(), 1024, 0);
resultBox.setCommandListener(this);
} finally {
if (is != null) is.close();
if (os != null) os.close();
if (c != null) c.close();
}
display.setCurrent(resultBox);
}
public void commandAction(Command c, Displayable d) {
if (c == clearCmd) { destroyApp(true); }
else if (c == callCmd) {
myName = nameField.getString();
try { invokeJSP(url); } catch (IOException ignored) {}
}
}
}
Content-Type: application/x-www-form-urlencoded,JSP 才能用 getParameter() 取值。name=value 格式寫入 OutputStream。