以下是test webpage,其中包含method="post"
我需要输入值并将结果页面打印到the console
。这是我的完整代码
import java.io.*;
import java.net.*;
import java.util.*;
class Post {
public static void main(String[] args) throws Exception {
URL url = new URL("http://chyngyz.com/test.php");
Map<String,Object> params = new LinkedHashMap<String,Object>();
params.put("fname", "Peter");
params.put("lname", "Pen");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0; System.out.print((char)c));
}
}
执行但打印原始页面。看起来似乎没有提交参数。我该如何改进我的代码?
这是我的test.php
<form method="post" action="testResult.php">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
这是我的testResult.php
<?php
$fname= $_POST['fname'];
$lname= $_POST['fname'];
?>
<p> Your name is
<?php
print $fname . ' ' . $lname;
?> </p>
答案 0 :(得分:2)
更改此行:
URL url = new URL("http://chyngyz.com/test.php");
由:
URL url = new URL("http://chyngyz.com/testResult.php");