站内搜索: 请输入搜索关键词
当前页面: 图书首页 > Wireless Java Developing with J2ME, Second Edition

Making a Connection with HTTP GET - Wireless Java Developing with J2ME, Second Edition

Previous Section Next Section

Making a Connection with HTTP GET

Loading data from a server is startlingly simple, particularly if you're performing an HTTP GET. Simply pass a URL to Connector's static open() method. The returned Connection will probably be an implementation of HttpConnection, but you can just treat it as an InputConnection. Then get the corresponding InputStream and read data to your heart's content.

In code, it looks something like this:

String url = "http://jonathanknudsen.com/simple";
InputConnection ic = (InputConnection)Connector.open(url);
InputStream in = ic.openInputStream();
// Read stuff from the InputStream
ic.close();

Most of the methods involved can throw a java.io.IOException. I've omitted the try and catch blocks from the example for clarity.

That's all there is to it. You can now connect your MIDlets to the world. The story is a little more complicated in MIDP 2.0 because network access is subject to security policies on the device. I'll talk more about this near the end of this chapter.

Passing Parameters

With HTTP GET, all parameters are passed to the server in the body of the URL. This makes it easy to send parameters to the server. The following code fragment shows how two parameters can be passed:

String url = "http://localhost/midp/simple?pOne=one+bit&pTwo=two";
InputConnection ic = (InputConnection)Connector.open(url);
InputStream in = ic.openInputStream();

The first parameter is named "pOne" and has "one bit" as a value; the second parameter is named "pTwo" and has "two" as a value.

A Simple Example

HTTP isn't all about exchanging HTML pages. It's actually a generic file-exchange protocol. In this section, we'll look at an example that loads an image from the network and displays it. Listing 9-1 shows the source code for ImageLoader, a MIDlet that retrieves an image from the Internet and displays it on the screen.

Listing 9-1: Retrieving an Image from the Internet
Start example
import java.io.*;

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

public class ImageLoader
    extends MIDlet
    implements CommandListener, Runnable {
  private Display mDisplay;
  private Form mForm;

  public ImageLoader() {
    mForm = new Form("Connecting...");
    mForm.addCommand(new Command("Exit", Command.EXIT, 0));
    mForm.setCommandListener(this);
  }

  public void startApp() {
    if (mDisplay == null) mDisplay = Display.getDisplay(this);
    mDisplay.setCurrent(mForm);

    // Do network loading in a separate thread.
    Thread t = new Thread(this);
    t.start();
  }

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {}

  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT)
      notifyDestroyed();
  }

  public void run() {
    HttpConnection hc = null;
    DataInputStream in = null;

    try {
      String url = getAppProperty("ImageLoader-URL");
      hc = (HttpConnection)Connector.open(url);
      int length = (int)hc.getLength();
      byte[] data = null;
      if (length != -1) {
        data = new byte[length];
        in = new DataInputStream(hc.openInputStream());
        in.readFully(data);
      }
      else {
        // If content length is not given, read in chunks.
        int chunkSize = 512;
        int index = 0;
        int readLength = 0;
        in = new DataInputStream(hc.openInputStream());
        data = new byte[chunkSize];
        do {
          if (data.length < index + chunkSize) {
            byte[] newData = new byte[index + chunkSize];
            System.arraycopy(data, 0, newData, 0, data.length);
            data = newData;
          }
          readLength = in.read(data, index, chunkSize);
          index += readLength;
        } while (readLength == chunkSize);
        length = index;
      }
      Image image = Image.createImage(data, 0, length);
      ImageItem imageItem = new ImageItem(null, image, 0, null);
      mForm.append(imageItem);
      mForm.setTitle("Done.");
    }
    catch (IOException ioe) {
      StringItem stringItem = new StringItem(null, ioe.toString());
      mForm.append(stringItem);
      mForm.setTitle("Done.");
    }
    finally {
      try {
        if (in != null) in.close();
        if (hc != null) hc.close();
      }
      catch (IOException ioe) {}
    }
  }
}

End example

The run() method contains all of the networking code. It's fairly simple; we pass the URL of an image (retrieved as an application property) to Connector's open() method and cast the result to HttpConnection. Then we retrieve the length of the image file, using the getLength() method. Given the length, we create a byte array and read data into it. Finally, having read the entire image file into a byte array, we can create an Image from the raw data.

If the content length is not specified, the image data is read in 512-byte chunks.

You'll need to specify the MIDlet property "ImageLoader-URL" in order for this example to work correctly. Note that you need to specify the URL of a PNG image, not of a JPEG or GIF. The URL http://65.215.221.148:8080/wj2/res/java2d_sm_ad.png produces the results shown in Figure 9-3.


Figure 9-3: The ImageLoader example

Previous Section Next Section