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?
/* 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With