Submit HTML form using Java

Java code

package post;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostForm
{
  public static void main(String[] args)
  {
    try
    {
      URL url = new URL( "http://www.aaaa.com/xyz.asp" );

      HttpURLConnection hConnection = (HttpURLConnection)
                             url.openConnection();
      HttpURLConnection.setFollowRedirects( true );

      hConnection.setDoOutput( true );
      hConnection.setRequestMethod("POST");	

      PrintStream ps = new PrintStream( hConnection.getOutputStream() );
      ps.print("param1=abcd&param2=10341");
      ps.close();

      hConnection.connect();

      if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
      {
        InputStream is = hConnection.getInputStream();
        OutputStream os = new FileOutputStream("output.html");
        int data;
        while((data=is.read()) != -1)
        {
          os.write(data);
        }
        is.close();
        os.close();
        hConnection.disconnect();
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }
}


Well, the above small program does the job pretty well. Submits a HTTP post request to the server and writes the response in an output file named as “output.html”.

Again, if you want the request method as GET, replace POST with GET in the above program.

You would have noticed the statement in above program “HttpURLConnection.setFollowRedirects( true );”. As I said in last post, it sets the redirection flag to be true. So if your web server, which you are going to hit, does redirection for processing and sending response back, you must add this statement.

Happy POSTing! Enjoy!

7 thoughts on “Submit HTML form using Java”

  1. @Ranganath

    Not yet. I used SGML parser ( written in VB .NET ) for discovering feeds during our college project.

    @PC

    Way to go! 🙂

  2. Hey can i know how to execute this …i tried with my relative URL…i wanted to know where actually you send data ie where do i post the data

    pls help me

    thanks and regards,

  3. @shail123

    You have to replace the URL addresss in the above program at line 16
    >>> URL url = new URL( “http://www.aaaa.com/xyz.asp” );

    and if you notice line 26 in program, you can pass param name and variables..
    >>> ps.print(“param1=abcd&param2=10341”);

    for your case, param1 is name and param2 is descrip. similarly with values.

Comments are closed.