Sun Java Solaris Communities My SDN Account Join SDN
 
FAQ

Emulating an HTML form in a J2ME application

 
 



Question

I am developing a project in J2ME (for MIDP 1.0 compliant devices) and I would like to create a program that emulates an HTML form.

For example, suppose I have the following form:

<FORM NAME="Example" METHOD="POST" ACTION="http://www.test.it">
<INPUT TYPE="TEXT" NAME="TextField">
<INPUT TYPE="TEXT" NAME="TextField2">
<INPUT TYPE="SUBMIT" NAME="Submit">
</FORM>

I would like to write a simple Java program that produces a form like the one above, but with the values "Hello" and "Hello2" instead of "TextField" and "TextField2." I tried to do this by coding the following:

import java.net.*;
import java.io.*;

...
try
{
    URL conn=new URL("http://www.test.it");
    URLConnection ConnAp=conn.openConnection();
    ConnAp.setDoOutput(true);
    PrintWriter out=new PrintWriter(ConnAp.getOutputStream());
    out.println("TextField=Hello;TextField2=Hello2");
    out.flush();
    out.close();
} catch(Exception ex)
{ System.out.println(ex.toString());}

But that didn't work. How can I do it?

Tip

What you code depends on whether you expect data returned in the response. If you expect no data in the response, try this:

HttpConnection conn =
("http://www.test.it" + "?TextField=Hello&TextField2=Hello2&Submit=Submit");
conn.close();

Note however that this simple request doesn't handle all the internationalization capabilities of a MIME-type POST request.

If you do expect data returned, you need to code something more sophisticated. For example, the following code handles a "full-blown" POST request, that is, one that includes MIME-type and urlencoded FORM data:

HttpConnection conn = (HttpConnection)
    Connector.open("http://www.test.it");

byte [] data = "TextField=Hello&TextField2=Hello2&Submit=Submit".getBytes ();

conn.setMethod (HttpConnection.POST);

conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");

conn.setRequestProperty("Content-Language", "en-US");

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

OutputStream os = conn.openOutputStream ();
os.write (data);
os.close ();
conn.close ();

You can find the HttpConnection interface in the javax.microedition.io package in MIDP.

Acknowledgments

Many thanks to Gary Adams for the solution to this question.

.
. . .
. Note: If you have a question to which you need an answer, try the Mobility Forums. You can read through the existing topics or register for your free Sun Developer Network membership and post new messages or threads. For more information, go to the Why Register page. .
.
.

Back To Top