Read from URL : StreamConnection « J2ME « Java Tutorial






import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class J2MEHttpExample extends MIDlet implements CommandListener {
  private Command exit= new Command("Exit", Command.EXIT, 1), start= new Command("Start", Command.EXIT, 1);

  private Display display;

  private Form form = new Form("Customer Ranking");
  public J2MEHttpExample() {
    display = Display.getDisplay(this);
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
  }

  public void startApp() throws MIDletStateChangeException {
    display.setCurrent(form);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
      destroyApp(false);
      notifyDestroyed();
    } else if (command == start) {
      StreamConnection connection = null;
      InputStream in = null;
      StringBuffer buffer = new StringBuffer();
      try {
        connection = (StreamConnection) Connector.open("http://www.a.com/");
        in = connection.openInputStream();
        int ch;
        while ((ch = in.read()) != -1) {
          if (ch != '\n') {
            buffer.append((char) ch);
          } else {
            String line = new String(buffer.toString());
            if (line.equals("o")) {
              int position = line.indexOf("alt=");
              Alert alert = new Alert("Alert", line.substring(position + 5, position + 8), null,
                  null);
              alert.setTimeout(Alert.FOREVER);
              alert.setType(AlertType.ERROR);
              display.setCurrent(alert);
            }
            buffer = new StringBuffer();
          }
        }
      } catch (IOException error) {
        Alert alert = new Alert("Error", "Cannot connect", null, null);
        alert.setTimeout(Alert.FOREVER);
        alert.setType(AlertType.ERROR);
        display.setCurrent(alert);
      }
    }
  }
}








31.44.StreamConnection
31.44.1.Load text file from a URL
31.44.2.Read from URL