Slide 5.6: Fetching a page using a StreamConnection (cont.)
  Slide 5.8: Fetching a page using an HttpConnection (cont.)
  Home


Fetching a Page Using an HttpConnection


Similar to the last example, this example fetches a page, but instead uses an HttpConnection. The Connector.open method opens a URL and returns an HttpConnection object. When you open the input stream, the connection is opened and the HTTP headers read. The c.getLength gets the content length, and if you want to get the content type, use the c.getType method.

 SecondExample.java 

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


/******************************************************************
*    An example MIDlet to fetch a page using an HttpConnection    *
*******************************************************************/

public class  SecondExample  extends MIDlet {
  private Display  display;
  private String   url = "http://people.aero.und.edu/~wenchen/hello.txt";
    
  public  SecondExample( ) {
    display = Display.getDisplay( this );
  }


  /******************************************************************
  *        startApp is invoked when the MIDlet is activated.        *
  *******************************************************************/
  public void  startApp( ) {
    // The specified URL is overridden in the descriptor.
    try {
      downloadPage( url );
    } catch( IOException e ) {
      // Handle the exception.
    }
  }


  private void  downloadPage( String url )  throws IOException {
    StringBuffer    b = new StringBuffer( );
    InputStream    is = null;
    HttpConnection  c = null;
    TextBox         t = null;
    try {
      long len = 0 ;
      int   ch = 0;
      c   = (HttpConnection) Connector.open( url );
      is  = c.openInputStream( );
      len = c.getLength( );
      if( len != -1 ) {
        // Read exactly Content-Length bytes.
        for ( int i = 0;  i < len;  i++ ) {
          if ( (ch = is.read( )) != -1 ) {
	    b.append( (char) ch );
          }
        }
      } else {
        // Read until the connection is closed.
	while ( (ch = is.read( )) != -1 ) {
          len = is.available( );
          b.append( (char) ch );
        }
      }
      t = new TextBox( "hello again....", b.toString( ), 1024, 0 );
    } finally {
      is.close( );
      c.close( );
    }
    display.setCurrent( t );
  }


  /******************************************************************
  *                      Pause, discontinue....                     *
  *******************************************************************/
  public void  pauseApp( ) { }


  /******************************************************************
  *                 Destroy must cleanup everything.                *
  *******************************************************************/
  public void  destroyApp( boolean unconditional ) { }
}