J2ME : A complete HTTP Client
Author : Jbuenol
From TechnologicalWiki
This article shows how to create a Hello World example for a MIDlet. The client receives a Hello World Message from the server.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HTTPHelloWorld extends MIDlet implements CommandListener, Runnable {
private Alert alert;
private Command exit,connect;
private Display screen;
private Form main;
private TextField ftext;
public HTTPHelloWorld() {
/* this is the main screen of the MIDlet*/
main = new Form("HTTP Connection");
ftext=new TextField("Readed Text:","",30,TextField.ANY);
connect = new Command("Connect",Command.SCREEN,0);
exit = new Command("Exit",Command.EXIT,0);
main.append(ftext);
/* command to connect to the server */
main.addCommand(connect);
main.append(exit);
main.setCommandListener(this);
}
/* This method is called at the beginning of the execution (MIDlet)*/
public void startApp() {
screen = Dispaly.getDisplay(this);
screen.setCurrent(principal);
ftext.setString("Push connect ... ");
}
/* MIDlet method */
public void pauseApp() {};
/* MIDlet method */
public void destroyApp( boolean unconditional ) {}
public commandAction(Command command, Displayable screenable) {
if (command == exit) {
destroyApp(true);
notifyDestroyed();
} else if (command == connect) {
/* when connect is the connect pushed, the connection thread will be thrown */
Thread t = new Thread(this);
t.start();
}
}
public void connect() {
HttpConnection connection = null;
InputStream input = null;
int length;
byte[] text;
String str;
try {
ftext.setString("Connecting...");
connection = (HttpConnection) Connector.open("http://mysever/helloWorld.php");
ftext.setString("Opening...");
input = connection.openInputStream();
length = ( int ) connection.getLength();
if ( length == - 1){
length = 255;
}
text = new byte[length];
ftext.setString("Reading...");
length = input.read(text);
input.close();
connection.close();
str = new String(text,0,length);
ftext.setString(str);
} catch ( Exception error ) {
/* an error has occurred */
alert = new Alert("Error Connecting",error.toString(),null,AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
screen.setCurrent(alert);
}
}
public void run() {
connect();
}
}


