Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to an html POST form using Java

Tags:

java

I have an HTML form that looks about like this:

<form name="form1" method="post" action="/confirm.asp">
    <input type="text" name="data1" size="20" value=""><br>
    <input type="text" name="data2" size="20" value=""><br>
    <input type="Submit" name=submit value="Submit">
</form>

I want to use Java to pass data todata1 and data2 and read the page that follows when the form is submitted. Since this is a method=post, I cannot use http://somesite.com/confirm.asp?data1=foo&data2=foo.

Can one please help?

like image 526
Christina Stewart Avatar asked Jul 16 '12 02:07

Christina Stewart


1 Answers

/* create a new URL and open a connection */
URL url = new URL("http://somesite.com/confirm.asp");
URLConnection con = url.openConnection();
con.setDoOutput(true);

/* wrapper the output stream of the connection with PrintWiter so that we can write plain text to the stream */
PrintWriter wr = new PrintWriter(con.getOutputStream(), true);

/* set up the parameters into a string and send it via the output stream */
StringBuilder parameters = new StringBuilder();
parameters.append("data1=" + URLEncoder.encode("value1", "UTF-8"));
parameters.append("&");
parameters.append("data2=" + URLEncoder.encode("value2", "UTF-8"));
wr.println(parameters);
wr.close();

/* wrapper the input stream of the connection with BufferedReader to read plain text, and print the response to the console */
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = br.readLine()) != null) System.out.println(line);
br.close();
like image 85
Eng.Fouad Avatar answered Sep 30 '22 20:09

Eng.Fouad