使用 Java 将数据传递到 html POST 表单

Chr*_*art 5 java

我有一个看起来像这样的 HTML 表单:

<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>
Run Code Online (Sandbox Code Playgroud)

我想用Java来传递数据data1data2和读取表单提交时下面的页面。由于这是一个 method=post,我不能使用http://somesite.com/confirm.asp?data1=foo&data2=foo.

可以帮忙吗?

Eng*_*uad 4

/* 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();
Run Code Online (Sandbox Code Playgroud)