An example MIDlet to invoke a CGI script (POST method is used). : HttpConnection « J2ME « Java Tutorial






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

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;

public class InvokeCgiMidlet2 extends MIDlet {

  private Display display;

  String url = "http://www.g.com/get.cgi";

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

  public void startApp() {
    try {
      getGrade(url);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  void getGrade(String url) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    StringBuffer b = new StringBuffer();
    TextBox t = null;
    try {
      c = (HttpConnection) Connector.open(url);
      c.setRequestMethod(HttpConnection.POST);
      c.setRequestProperty("CONTENT-TYPE", "application/x-www-form-urlencoded");
      c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
      c.setRequestProperty("Content-Language", "en-CA");
      os = c.openOutputStream();

      String str = "name=1";
      byte postmsg[] = str.getBytes();
      for (int i = 0; i < postmsg.length; i++) {
        os.write(postmsg[i]);
      }
      os.flush();
      is = c.openDataInputStream();
      int ch;
      while ((ch = is.read()) != -1) {
        b.append((char) ch);
      }
      t = new TextBox("Final Grades", b.toString(), 1024, 0);
    } 
    display.setCurrent(t);
  }
}








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