Deal with cookie with J2ME : Cookie « J2ME « Java Tutorial






import java.io.InputStream;

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.TextField;
import javax.microedition.midlet.MIDlet;

public class HttpCookieMIDlet extends MIDlet implements CommandListener {
  private Command exitCommand= new Command("Exit", Command.EXIT, 1);

  private Command sendCommand= new Command("Send", Command.OK, 1);

  private Command backCommand = new Command("Upload", Command.OK, 1);

  private Display display;

  private String URL = "http://localhost/all_http.asp";

  private String sessionID;

  private Form mainForm;

  private TextField URLField = new TextField(null, URL, 250, TextField.URL);

  public HttpCookieMIDlet() {
    display = Display.getDisplay(this);
  }

  public void startApp() {
    mainForm = new Form("Address");
    mainForm.append(URLField);
    mainForm.addCommand(sendCommand);
    mainForm.addCommand(exitCommand);
    mainForm.setCommandListener(this);
    display.setCurrent(mainForm);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    if (c == sendCommand)
      send(URLField.getString());
    else if (c == backCommand) {
      URLField.setString(URL);
      display.setCurrent(mainForm);
    } else {
      destroyApp(false);
      notifyDestroyed();
    }
  }

  public void send(String url) {
    HttpConnection hpc = null;
    InputStream is = null;

    try {
      hpc = (HttpConnection) Connector.open(url);
      if (sessionID != null)
        hpc.setRequestProperty("cookie", sessionID);
      is = hpc.openInputStream();

      String cookie = hpc.getHeaderField("Set-cookie");
      if (cookie != null) {
        int position = cookie.indexOf(';');
        sessionID = cookie.substring(0, position);
      }

      int length = (int) hpc.getLength();
      byte[] response = new byte[length];
      is.read(response);
      String strResponse = new String(response);
      URLField.setString(strResponse);
    } catch (Exception e) {
      System.out.println("xxx :error");
    } finally {
      try {
        if (is != null)
          is.close();
        if (hpc != null)
          hpc.close();
      } catch (Exception e) {
      }
    }
  }
}








31.39.Cookie
31.39.1.Use Cookie
31.39.2.Deal with cookie with J2ME