Call asp page from J2ME : Connector « J2ME « Java Tutorial






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

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
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.midlet.MIDlet;

public class CookieMIDlet extends MIDlet {
  private Display mDisplay;

  private Form mForm;

  private String mSession;

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

    mForm = new Form("CookieMIDlet");

    mForm.addCommand(new Command("Exit", Command.EXIT, 0));
    mForm.addCommand(new Command("Send", Command.SCREEN, 0));
    mForm.setCommandListener(new CommandListener() {
      public void commandAction(Command c, Displayable s) {
        if (c.getCommandType() == Command.EXIT)
          notifyDestroyed();
        else
          send();
      }
    });

    mDisplay.setCurrent(mForm);
  }

  private void send() {
    String url = "http://localhost/http.asp";

    try {
      HttpConnection hc = (HttpConnection) Connector.open(url);
      if (mSession != null)
        hc.setRequestProperty("cookie", mSession);
      InputStream in = hc.openInputStream();

      String cookie = hc.getHeaderField("Set-cookie");
      if (cookie != null) {
        int semicolon = cookie.indexOf(';');
        mSession = cookie.substring(0, semicolon);
      }

      int length = (int) hc.getLength();
      byte[] raw = new byte[length];
      in.read(raw);

      String s = new String(raw);
      Alert a = new Alert("Response", s, null, null);
      a.setTimeout(Alert.FOREVER);
      mDisplay.setCurrent(a, mForm);

      in.close();
      hc.close();
    } catch (IOException ioe) {
      Alert a = new Alert("Exception", ioe.toString(), null, null);
      a.setTimeout(Alert.FOREVER);
      mDisplay.setCurrent(a, mForm);
    }
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }
}








31.40.Connector
31.40.1.Image Loader
31.40.2.URL query
31.40.3.Call asp page from J2ME
31.40.4.Http Get with J2ME
31.40.5.Http header
31.40.6.Load image from a URL
31.40.7.Check Http connection returning code
31.40.8.Http post