NetTest2.java



import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class NetTest2 extends MIDlet
                      implements ItemStateListener {

    public Form form;
    public Ticker ticker;
    public ChoiceGroup choice;

    public void startApp() {
        form = new Form( "Network Test" );
        ticker = new Ticker( "" );
        form.setTicker( ticker );

        String[] nums = { "1", "2", "3" }; 
        choice = new ChoiceGroup( "Select Number", Choice.EXCLUSIVE,
                              nums, null );
        form.append( choice );
        form.setItemStateListener( this );

        Display.getDisplay( this ).setCurrent( form );
    }

    public void pauseApp() {
    }

    public void destroyApp( boolean flag ) {
    }

    public void itemStateChanged( Item item ) {

        if( item == choice ) {
            String num = choice.getString( choice.getSelectedIndex() );
            String message = getMessage( num );
            ticker.setString( message );
        }
    }

    public String getMessage( String num ) {

        String message = null;
        try {
            HttpConnection connection
               = (HttpConnection)Connector.open(
                   "http://10.16.128.57:8080/examples/servlet/SelectMessage",
                    Connector.READ_WRITE, true );
            connection.setRequestMethod( HttpConnection.POST );
            connection.setRequestProperty( "Content-Type", "text/plain" );

            OutputStream out = connection.openOutputStream();
            out.write( num.getBytes() );
            out.close();

            InputStream in = connection.openInputStream();
            InputStreamReader reader = new InputStreamReader( in );
            StringBuffer sb = new StringBuffer();
            int i=0;
            while( ( i = reader.read() ) != -1 ) {
                 char c = ( char )i;
                 sb.append( c );
            }
            reader.close();
            in.close();
            connection.close();
            message = sb.toString();
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
        return message;
    }
}