PAGES

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.
Connector.open 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 "http://www.sitename.com"
Ex:- "http://www.Google.com" ,"http://www.yahoo.com"
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 202.12.22.13
then you can use: "http://202.12.22.13:8080" 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.*;
import java.io.*;
import javax.microedition.io.*;

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");
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
  }
  public void startApp() throws MIDletStateChangeException
  {
    Display.getDisplay(this).setCurrent(form);
  }
  public void pauseApp()
  {
  }
  public void destroyApp(boolean unconditional)
  {
  }
  public void commandAction(Command command, Displayable displayable)
  {
    if (command == exit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (command == start)
    {
        Thread thread1 = new Thread(this);
        thread1.start();
        System.out.println("Thread Started");
    }
  }
  public void run()
          {
   try
      {
       HttpConnection connection = (HttpConnection) Connector.open("http://www.google.com");
       PrintStream output =new PrintStream(connection.openOutputStream() );
       output.println( "GET /my.html HTTP/1.0 \n" );
       output.flush();
       InputStream in = connection.openInputStream();

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

      int ch;
       while( ( ch = in.read() ) != -1 )
      {
         System.out.print( (char) ch );
       }
    
       in.close();
       output.close();
       connection.close();
     }
      catch( Exception error )
       {
         Alert alert = new Alert("Error", "Cannot access URL.", null, null);
         alert.setTimeout(Alert.FOREVER);
         alert.setType(AlertType.ERROR);
         Display.getDisplay(this).setCurrent(alert);
        }
  }
}


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 = dataInputStream.read()) != -1)
      {
       results.append((char) inputChar);
      }
    
      // display the page contents on the phone screen
      StringItem resultField = new StringItem(null, results.toString());
      form.append(resultField);


2 comments:

customised by Vaibhav