Invoking Remote Applications from MIDlets

Now let’s look at some examples of fetching HTTP pages and invoking CGI scripts and servlets from MIDlets using the connection framework.

Fetching a Page

Example 7-1 shows how to read the contents of a file referenced by a URL, using a StreamConnection . An HttpConnection can also be used, but since no HTTP-specific behavior is needed here, the StreamConnection is used. The application is very simple. The Connector.open( ) method opens a connection to the URL and returns a StreamConnection object. Then an InputStream is opened through which to read the contents of the file, one character at a time, until the end of the file (signaled by a character value of -1) is reached. In the event that an exception is thrown, both the stream and connection are closed.

Example 7-1. Fetching a page referenced by a URL

import java.io.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class FetchPageMidlet extends MIDlet { private Display display; String url = "http://www.javacourses.com/hello.txt"; public FetchPageMidlet( ) { display = Display.getDisplay(this); } /** * This will be invoked when we start the MIDlet */ public void startApp( ) { try { getViaStreamConnection(url); } catch (IOException e) { //Handle Exceptions any other way you like. System.out.println("IOException " + e); e.printStackTrace( ); } } /** * Pause, discontinue .... */ public void pauseApp( ) { } /** * Destroy must cleanup ...

Get Wireless Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.