Using Java to submit HTML form Post requests, newbie needs help!
807569Jun 4 2006 — edited Jun 5 2006Hi guys,
Ok I want to write a Java program which basically automatically fills out a form on a particular website which uses a post request to send the information to the server. Im using the Jakarta commons HttpClient, Logging and Codecs packages, and have the following code:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
public class Post2{
public Post2(){
String url = "A URL(extracted from the 'action' attribute in the form)";
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod( url );
// Configure the form parameters
method.addParameter( "author", "me" );
method.addParameter( "email", "email@email.com" );
method.addParameter( "title", "hello" );
method.addParameter( "action", "post" );
method.addParameter( "revise", "Login" );
method.addParameter( "update", "loginattempt" );
method.addParameter( "htmlpostison", "o checked" );
method.addParameter( "autorespond", "yes" );
method.addParameter( "preview", "Preview" );
method.addParameter( "submit", "Post!" );
method.addParameter( "respondtitle", "" );
method.addParameter( "parent", "0" );
method.addParameter( "messageid", "0" );
method.addParameter( "username", "" );
method.addParameter( "password", "" );
method.addParameter( "edit", "" );
// Execute the POST method
int statusCode = client.executeMethod( method );
if( statusCode != -1 ) {
String contents = method.getResponseBodyAsString();
method.releaseConnection();
System.out.println( contents );
}
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
Basically what i've done here is gone through the HTML code for the page, found all of the INPUT tags, and added them as parametes with some values. Some are type="hidden", type="submit" etc, do I need all of these?
Is this the right approach because its not working?! This should post a message to the particular forum as if filling in the HTML form. This is just a research project of mine to see if this kind of thing is possible in Java!
Any suggestions greatly appreciated.