【发布时间】:2018-02-09 21:37:40
【问题描述】:
代码的目的是将参数插入表单,然后提交表单,表单又将数据输入 MySQL 数据库。问题是该方法不发布数据。我不确定我做错了什么,我已经查看了很多关于此的问题,但似乎没有任何效果。
这是表格。
<form action="http://localhost/Documents/dataadded.php" method="post">
<b>Add a New Data</b>
<p>Email Address:
<input type="text" name="email_address" size="30" value="" />
</p>
<p>Email Pass:
<input type="text" name="email_pass" size="30" value="" />
</p>
<p>
<input type="submit" name="submit" value="Send" />
</p>
</form>
这里是 Java 代码。
public static void main(String[] args) {
String key1 = "email_address";
String key2 = "email_pass";
String key3 = "submit";
String param1 = "testemail@gmail.com";
String param2 = "password123";
String param3 = "Send";
try {
URL website = new URL("http://localhost/Documents/added.php");
Map<String,String> arguments = new LinkedHashMap<>();
arguments.put(key1, param1);
arguments.put(key2, param2);
arguments.put(key3, param3);
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(length);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setDoOutput(true);
connection.getOutputStream().write(out);
System.out.println(sj.toString());
InputStream response = connection.getInputStream();
@SuppressWarnings("resource")
Scanner scan = new Scanner(response);
String responsebody = scan.useDelimiter("\\A").next();
System.out.println(responsebody);
} catch (IOException e) {
e.printStackTrace();
}
}
如果有人能阐明代码有什么问题,我们将不胜感激。
【问题讨论】:
-
PHP是如何参与的?
-
当表单提交时,数据被传递给localhost/Documents/dataadded.php,它有PHP代码处理数据并将其添加到数据库中。
-
@C.Trant 但这实际上与您的问题有关吗?你如何处理数据似乎无关紧要,你的问题是数据的传递
-
Java代码中的URL与表单中的不同。
-
是的,我的错,我发的第一篇文章,它建议了 php 标签和其他标签,所以我点击了它们。
标签: java http httpurlconnection