"Never stand begging for what you have the power to earn."

How to submit HTML form data (method=POST) using JAVA

The following is an example of how to "emulate" a browser and sumbit arbitrary data to a form handler (using POST in this case) and http or https.
For instance, you have the following HTML form:
and you would like to use your JAVA program to submit the information and get the feedback rather than use the browser.

The form handler itself is not important here. What matters is that you know what information you have to submit - your best bet is to look at the actual html code of the form, since there may be hidden parameters that are passed to the handler (e.g. look for <input type="hidden" name="" value=""> tags). Also, it is a good idea to see if any cookies are being set (as a bonus, I'll show you how to pass cookies as well).

Here's a code snipped that does just this:
The method doSubmit takes two parameters - url and data. url is simply a string that contains the url of the form handler (e.g. http://somesite.com/loginhandler.php). data is a HashMap of the key/value pairs contained in the form (sounds more complicated than it really is). For instance, for our sample form above we would construct the following HashMap and invoke doSumit like this:
HashMap<String, String> data = new HashMap<String, String>();
data.put("username", "someuser");
data.put("password", "supersecret");
		
doSubmit("http://somesite.com/loginhandler.php, data);
Next we construct an HttpURLConnection object from the passed url (if you want to use https, change the class name to HttpsURLConnection). This class contains useful HTTP methods and we'll use this to communicate with the site.

After that we create an output stream and associate it with the http connection (DataOutputStream out = new DataOutputStream(conn.getOutputStream());). After that we loop through the keys and values in the HashMap and create the content that we want to send. The format for passing the arguments is the follwing:
key1=value1&key2=value2&key3=value3
and so on. The values have to be appropriately encoded (hence the calls to URLEncoder.encode(value, "UTF-8");.

Next we send the data and flush it and get the response (you might want to process this for to see if the server returned some kind of error while processing the data). And for the cookies, add the following line after creating the connection:
conn.setRequestProperty("Cookie", "cookiename1=cookievalue1; cookiename2=cookiename2");
And that's it. If you have any questions, email me at vxl2@dowling.edu.