代碼的目標是將參數插入到表單中,然後提交表單,然後將表單輸入到MySQL數據庫中。問題是該方法不會發布數據。我不確定我做錯了什麼,我已經看過這麼多的問題,但似乎沒有任何工作。無法使用Java發送帖子表格
這裏是表格。
<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 = "[email protected]";
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如何介入? –
當表單被提交時,數據被傳遞給http://localhost/Documents/dataadded.php,後者具有處理數據並將其添加到數據庫的PHP代碼。 –
@ C.Trant但是這實際上與你的問題有關嗎?如何處理數據看起來毫不相關,您的問題是傳遞數據 – GrumpyCrouton