Sunday, May 15, 2011

HTTP Connection in J2ME

 HTTP is a request-response protocol in which the parameters of request must be set before the request is sent.
 The connection exists in one of three states:

    * Setup, in which the request parameters can be set
    * Connected, in which request parameters have been sent and the response is expected
    * Closed, the final state, in which the HTTP connection as been terminated

To read a URL we can use StreamConnection.No HTTP specific behavior is needed or used. is used to open URL and a StreamConnection is returned.
First we open an output stream by the openOutputStream or openDataOutputStream  methods.
Then we send the get request along with the HTML format.
When the output stream is flushed via the OutputStream.flush or DataOutputStream.flush  methods,
the request parameters MUST be sent along with any data written to the stream.
When an output stream is closed via the OutputStream.close or DataOutputStream.close  methods,
the connection enters the Connected state.
The transition to Closed state from any other state is caused by the close method and the closing all
of the streams that were opened from the connection.
From the StreamConnection the InputStream is opened.
It is used to read every character until end of file (-1). If an exception is thrown the connection and stream are closed.

Here note that you have to give standard form URL like ""
Ex:- "" ,""
However you can also check it by running a localhost server like apache and glassfish.
Ex:- For apache server with 8080 port you can use "http://localhost:8080"

I came around many students who doubted whether their IP will work instead of localhost.
The answer is yes ,provided you have put the http connection in firewall exception.
So if your Ip is somewhat
then you can use: "" assuming port to be 8080.

One more problem that i faced a lot copying codes from famous j2me tutorial sites is they do all the connection work
in commandAction() itself which gives error
"Connection should be opened in thread other than CommandAction Handler"
So try to create seperate thread for avoiding deadlock and call the thread in commandAction().

Source Code:-

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class http extends MIDlet implements CommandListener,Runnable {
  private Command exit, start;
  private Form form;

  public http ()
    exit = new Command("Exit", Command.EXIT, 1);
    start = new Command("Start", Command.EXIT, 1);
    form = new Form("Browse");
  public void startApp() throws MIDletStateChangeException
  public void pauseApp()
  public void destroyApp(boolean unconditional)
  public void commandAction(Command command, Displayable displayable)
    if (command == exit)
    else if (command == start)
        Thread thread1 = new Thread(this);
        System.out.println("Thread Started");
  public void run()
       HttpConnection connection = (HttpConnection)"");
       PrintStream output =new PrintStream(connection.openOutputStream() );
       output.println( "GET /my.html HTTP/1.0 \n" );
       InputStream in = connection.openInputStream();

      //put the code for screen display here given at the end of the post

      int ch;
       while( ( ch = ) != -1 )
         System.out.print( (char) ch );
      catch( Exception error )
         Alert alert = new Alert("Error", "Cannot access URL.", null, null);

In this code the output will appear on output console of the IDE you are using.
If you want to see the output on mobile screen just add these lines at the location specified in the code(first read the code)
 DataInputStream dataInputStream = new DataInputStream(in);
      int inputChar;
      StringBuffer results = new StringBuffer();
      while ( (inputChar = != -1)
       results.append((char) inputChar);
      // display the page contents on the phone screen
      StringItem resultField = new StringItem(null, results.toString());


  1. This comment has been removed by the author.

  2. Thanks for sharing, I will bookmark and be back again

    J2ME Application Development


customised by Vaibhav