Posting a Form with HTTP POST

Team-Fly

Posting a form is a little more complicated on the MIDlet side. In particular, there are request headers that need to be set in HttpConnection before the server is contacted.

You've already seen how to do a POST in Chapter 2, in the Jargoneer example. The process works like this:

  1. Obtain an HttpConnection from Connector's open() method.

  2. Modify the header fields of the request. In particular, you need to change the request method by calling setRequestMethod(), and you should set the "Content-Length" header by calling setRequestProperty(). This is the length of the parameters you will be sending.

  3. Obtain the output stream for the HttpConnection by calling openOutputStream(). This sends the request headers to the server.

  4. Send the request parameters on the output stream returned from the HttpConnection.

  5. Read the response from the server from the input stream retrieved from HttpConnection's openInputStream() method.

Here it is in code, excerpted from Jargoneer.java.

 // Obtain an HttpConnection. HttpConnection c = null; c = (HttpConnection)Connector.open(kURL); // Set up the request headers. c.setRequestMethod(HttpConnection.POST); c.setRequestProperty("User-Agent",     "Profile/MIDP-1.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-US"); c.setRequestProperty("Content-Type",     "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length",     String.valueOf(mPostString.length())); // Write out the POST parameters. out = c.openOutputStream(); out.write(mPostString.getBytes()); out.flush(); // Now read the response. in = c.openInputStream(); 


Team-Fly


Wireless Java. Developing with J2ME
ColdFusion MX Professional Projects
ISBN: 1590590775
EAN: 2147483647
Year: 2000
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net