Submit HTML form using Java
Java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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!
Tags: Java, Programming, Technology, Web















nice …..
i used this to build mini search engine
hey good one man.. have u tried with the HTML parsing libraries in Java?
@Ranganath
Not yet. I used SGML parser ( written in VB .NET ) for discovering feeds during our college project.
@PC
Way to go!
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,
Hi ,
I have an URL http://www.something.com/test.asp
I want to post key and values to this URL…
ie if i want to pass the values name=abc
and descrip=testing it should give a response for the same
pls advice me on the same
Thanks and Regards,
@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¶m2=10341″);
for your case, param1 is name and param2 is descrip. similarly with values.
thanks for the script… it will be great! http://www.forms.com/
html Forms