Load Image with HttpConnection : HttpConnection « J2ME « Java Tutorial






import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;

public class ImageLoaderMIDlet extends MIDlet {
  private Item mItem;

  public void startApp() {
    final Display display = Display.getDisplay(this);

    Form mainForm = new Form("Loading...");
    display.setCurrent(mainForm);

    final Form imageForm = new Form("Image");
    imageForm.addCommand(new Command("Exit", Command.EXIT, 0));
    imageForm.setCommandListener(new CommandListener() {
      public void commandAction(Command c, Displayable s) {
        notifyDestroyed();
      }
    });

    Thread t = new Thread() {
      public void run() {
        try {
          String URL = "http://localhost/Duke.png";
          Image image = loadImage(URL);
          mItem = new ImageItem(null, image, 0, null);
        } catch (IOException ioe) {
          mItem = new StringItem(null, ioe.toString());
        }
        imageForm.append(mItem);
        display.setCurrent(imageForm);
      }
    };
    t.start();
  }

  public Image loadImage(String url) throws IOException {
    HttpConnection hpc = null;
    DataInputStream dis = null;
    try {
      hpc = (HttpConnection) Connector.open(url);
      int length = (int) hpc.getLength();
      byte[] data = new byte[length];
      dis = new DataInputStream(hpc.openInputStream());
      dis.readFully(data);
      return Image.createImage(data, 0, data.length);
    } finally {
      if (hpc != null)
        hpc.close();
      if (dis != null)
        dis.close();
    }
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }
}








31.37.HttpConnection
31.37.1.An example MIDlet to fetch a page using an HttpConnection
31.37.2.Use HttpConnection
31.37.3.An example MIDlet to invoke a CGI script (POST method is used).
31.37.4.Load Image with HttpConnection
31.37.5.Response Header