Listing 2: Using HTTP connections in the MIDlet FetchPage

// Part of commandAction() handling the FETCH event.

// Open a HTTP connection to the target URL.
HttpConnection conn = (HttpConnection) Connector.open( url );
conn.setRequestMethod(HttpConnection.GET);

// Get the response stream from the server.
DataInputStream is = conn.openDataInputStream();

// Read the data from the stream into a String.
// The reader truncates above "length" (2048 bytes)
// to avoid memory overflow.
StringBuffer pageContentBuff = new StringBuffer();
int ch, i = 0;
while ( ((ch = is.read()) != -1) && (i < length) ) {
  pageContentBuff.append( (char)ch );
  i++;
}
pageContent = pageContentBuff.toString();

// Close the connection.
is.close();
conn.close();
— End of Listing —