Java Reference
In-Depth Information
Obtain an HttpConnection from Connector 's open() method.
1.
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.
Send the request parameters on the output stream returned from the HttpConnection .
Parameters should be encoded as described earlier (and in the documentation for the
J2SE class java.net.URLEncoder , see http://java.sun.com/j2se/1.4.2/docs/api/java/
net/URLEncoder.html ).
4.
5.
Read the response from the server from the input stream retrieved from
HttpConnection 's openInputStream() method.
The following example, Listing 10-2, demonstrates how to send a single parameter to a
server using an HTTP POST. Multiple parameters can be assembled by joining them with an
ampersand separator. Note that the parameter in this example has been encoded as described
previously. In this example, the parameter value “Jonathan Knudsen!” has been encoded to
“Jonathan+Knudsen%21”. Listing 10-3 shows a very simple servlet that can communicate with
PostMIDlet .
Listing 10-2. A Simple MIDlet Performing an HTTP POST
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class PostMIDlet
extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
public PostMIDlet() {
mForm = new Form("Connecting...");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
}
public void startApp() {
if (mDisplay == null) mDisplay = Display.getDisplay(this);
mDisplay.setCurrent(mForm);
Search WWH ::




Custom Search