Example

To understand the MIDP networking APIs, it's a good idea to look at an example. Let's step through the code from HttpNetworking.java, which is a simple example that downloads a page from a Web server using HTTP.

private String getPage(String url) throws IOException {
  HttpConnection c = null;
  String result = null;
  try {
    c = (HttpConnection)Connector.open(url);
    DataInputStream dis = c.openDataInputStream();
    byte[] buffer = new byte[(int)c.getLength()];
    dis.readFully(buffer);
    result = new String(buffer);
  }
  catch (Exception e) {
    Alert alert = new Alert("Error");
    alert.setString(e.toString());
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert, mainForm);
    System.out.println(e.getMessage());
  }
  finally {
    if(c != null)
      c.close();
  }
  return result;
}

In this simple example, we use a Connector to open an HttpConnection, which we use to open an input stream. To download the first bytes of the page at the specified URL, we use the read() method on the input stream to read the bytes into a byte array. The number of bytes downloaded equals the size of the byte array.

So, what's happening under the covers in this code? First, and perhaps counterintuitively, the HTTP connection is not actually made when the open method is called on the Connector. At this point, the HttpConnection is considered to be in "Setup" state; the HTTP connection has not yet been made with the server. A connection is made and data is sent and received when one of the following methods is called, causing the HttpConnection to transition from the "Setup" state to the "Connected" state:

  • openInputStream

  • openOutputStream

  • openDataInputStream

  • openDataOutputStream

  • getLength

  • getType

  • getEncoding

  • getHeaderField

  • getResponseCode

  • getResponseMessage

  • getHeaderFieldInt

  • getHeaderFieldDate

  • getExpiration

  • getDate

  • getLastModified

  • getHeaderField

  • getHeaderFieldKey

To test this example, in the commandAction method of HttpNetworking.java we can use the following code to download the HttpNetworking.html test page, which contains the following:

This is a test page for the HttpNetworking application.

The commandAction method contains:

public void commandAction(Command c, Displayable d) {
  try {
    if (c == getCommand) {
      resultItem.setLabel("Requesting page...");
      resultItem.setText("");
      String result = getPage(
        "http://users.bigpond.com/ripple/JavaOnPDAs/HttpNetworking.html");
      // String result = getPage(
      //   "http://192.168.0.3:5555/ripple/JavaOnPDAs/HttpNetworking.html");
      resultItem.setLabel("Received...");
      resultItem.setText(result);
    }
    else if (c == exitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
  catch (Exception e) {
    e.printStackTrace();
    resultItem.setLabel("Error:");
    resultItem.setText(e.toString());
  }
}

When the application is run, we get a screen that resembles that of Figure 7.2.

Figure 7.2. HttpNetworking

graphics/07fig02.gif

In our simple example, the connection is made when the openDataInputStream method is called. To look at what's going on under the covers, we can use a tool called tcpmon to look at the exchange between the Palm device and the Web server. The tcpmon tool comes with Axis, a Web services toolkit from Apache that we will be using in a subsequent chapter.[3] We can use tcpmon to set up a TCP/IP tunnel between port 5555 on the hostname localhost and port 80 on the hostname users.bigpond.com where the test page HttpNetworking.html is located. tcpmon will show all the TCP/IP traffic passing through the tunnel.

[3] For some instructions on setting up Axis, refer to "Setting Up Axis and Tomcat" on page 158.

Note that if you try this on a real Palm device (instead of the Palm Emulator), you will need to use the host PC's IP address in the URL in the source code rather than localhost. The reason is that the Palm interprets localhost as itself, and not the PC. localhost works on the Palm Emulator because all TCP/IP requests are forwarded to the host PC. You can find out the PC's IP address by opening a command line and typing ipconfig. Depending on the PC's configuration, it will display the IP address to the use in the URL. In the following ipconfig response, the IP address to use is 192.168.0.1:

C:\>ipconfig

Windows 2000 IP Configuration

Ethernet adapter Local Area Connection:

        Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . : 192.168.0.1
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . :

PPP adapter Big Pond:

        Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . : 203.54.22.217
        Subnet Mask . . . . . . . . . . . : 255.255.255.255
        Default Gateway . . . . . . . . . : 203.54.22.217

In this case, you need to change the URL in the commandAction method to http://192.168.0.1:5555/ripple/JavaOnPDAs/HttpNetworking.html.

On tapping the Get button, the HttpNetworking application makes the connection and sends the following request:

GET /ripple/JavaOnPDAs/HttpNetworking.html HTTP/1.1


Host: users.bigpond.com

Content-Length: 0

The Web server replies as follows:

HTTP/1.1 200 OK


Server: Microsoft-IIS/5.0


Date: Sun, 08 Dec 2002 05:14:57 GMT


Content-Type: text/html


Accept-Ranges: bytes


Last-Modified: Sun, 08 Sep 2002 07:43:07 GMT


ETag: "82ee595fb57c21:1508"


Content-Length: 55


This is a test page for the HttpNetworking application.

How to Recognize Problems

If the Web server is not listening on the port specified in the open method, or if the URL is unreachable, the openInputStream method will throw an IOException.

If the URL is invalid (for example, if we passed "http://illegalurl:5555/index.html" to the open method), the openInputStream method throws a ConnectionNotFoundException.

If the protocol specified is invalid (for example, if we passed "htttp://127.0.0.1:5555/index.html" to the open method), the open method throws a ConnectionNotFoundException, with the message "The requested protocol does not exist htttp://127.0.0.1:5555/index.html."

Finally, if networking is not enabled on the Palm, a helpful message will be displayed when a network connection is attempted, as shown in Figure 7.3.

Figure 7.3. Error displayed when networking is not enabled

graphics/07fig03.gif