Mục tiêu của mã là chèn các tham số vào biểu mẫu rồi gửi biểu mẫu để lần lượt nhập dữ liệu vào cơ sở dữ liệu MySQL. Vấn đề là phương thức không đăng dữ liệu. Tôi không chắc mình đang làm gì sai, tôi đã xem xét rất nhiều câu hỏi về vấn đề này nhưng dường như không có gì hiệu quả.Không thể gửi biểu mẫu bài đăng trong Java
Đây là biểu mẫu.
<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>
Đây là mã 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();
}
}
Nếu ai đó có thể làm sáng tỏ điều gì sai với mã, nó sẽ được đánh giá cao.
PHP tham gia như thế nào? –
Khi biểu mẫu được gửi, dữ liệu được chuyển tới http: //localhost/Documents/dataadded.php có mã PHP xử lý dữ liệu và thêm nó vào cơ sở dữ liệu. –
@ C.Trant Nhưng thực sự có liên quan đến câu hỏi của bạn không? Cách bạn xử lý dữ liệu có vẻ không liên quan, vấn đề của bạn là truyền dữ liệu – GrumpyCrouton