Skip to content

Instantly share code, notes, and snippets.

@roylee0704
Created October 13, 2024 05:33
Show Gist options
  • Save roylee0704/11f38017349dabe5139bd45ce19cb9d9 to your computer and use it in GitHub Desktop.
Save roylee0704/11f38017349dabe5139bd45ce19cb9d9 to your computer and use it in GitHub Desktop.
Connect to https via j2me
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpsConnectionExample extends MIDlet implements CommandListener {
private Display display;
private Form form;
private StringItem resultItem;
private Command exitCommand;
private Command connectCommand;
public HttpsConnectionExample() {
display = Display.getDisplay(this);
form = new Form("HTTPS Connection Example");
resultItem = new StringItem("Result: ", "");
exitCommand = new Command("Exit", Command.EXIT, 1);
connectCommand = new Command("Connect", Command.SCREEN, 1);
form.append(resultItem);
form.addCommand(exitCommand);
form.addCommand(connectCommand);
form.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
} else if (c == connectCommand) {
new Thread(new Runnable() {
public void run() {
connectHttps();
}
}).start();
}
}
private void connectHttps() {
HttpsConnection connection = null;
InputStream is = null;
try {
connection = (HttpsConnection) Connector.open("https://api.example.com");
connection.setRequestMethod(HttpsConnection.GET);
int responseCode = connection.getResponseCode();
if (responseCode == HttpsConnection.HTTP_OK) {
is = connection.openInputStream();
int length = (int) connection.getLength();
byte[] data;
if (length != -1) {
data = new byte[length];
is.read(data);
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
baos.write(ch);
}
data = baos.toByteArray();
}
final String response = new String(data);
display.callSerially(new Runnable() {
public void run() {
resultItem.setText("Response: " + response);
}
});
} else {
display.callSerially(new Runnable() {
public void run() {
resultItem.setText("HTTP Error: " + responseCode);
}
});
}
} catch (final Exception e) {
display.callSerially(new Runnable() {
public void run() {
resultItem.setText("Error: " + e.toString());
}
});
} finally {
try {
if (is != null) is.close();
if (connection != null) connection.close();
} catch (Exception e) {}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment