import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class WebFormArchiver {
private static final String ARCHIVE_FILE = "form_archive.txt"; // File to store form data
public static void archiveFormData(String formUrl) {
try {
URL url = new URL(formUrl);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// Get form data as a string
String formData = getFormDataAsString(url);
// Append data to the archive file
appendFormDataToArchive(formData);
} catch (MalformedURLException e) {
System.err.println("Error: Invalid URL - " + formUrl);
// Log the error or handle it appropriately
} catch (IOException e) {
System.err.println("Error: Could not access URL - " + formUrl);
// Log the error or handle it appropriately
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
//Log the error or handle it appropriately
}
}
private static String getFormDataAsString(URL url) throws IOException {
// Send a POST request to the URL
try (java.io.OutputStream outputStream = url.getOutputStream()) {
outputStream.write(getFormDataBytes(new HashMap<>()));
}
// Read the response from the server
java.io.BufferedReader reader = new java.io.BufferedReader(url.openStream(), java.nio.charset.StandardCharsets.UTF_8);
return reader.ReadToEnd();
}
private static byte[] getFormDataBytes(Map<String, String> formData) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : formData.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
String formString = sb.toString();
return formString.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
private static void appendFormDataToArchive(String formData) {
try {
java.io.FileWriter writer = new java.io.FileWriter(ARCHIVE_FILE, formData);
writer.append("\n"); // Add a newline between form data entries
writer.close();
} catch (IOException e) {
System.err.println("Error: Could not write to archive file - " + e.getMessage());
//Log the error or handle it appropriately
}
}
public static void main(String[] args) {
// Example usage
String formUrl1 = "https://www.example.com/form1";
String formUrl2 = "https://www.example.com/form2";
archiveFormData(formUrl1);
archiveFormData(formUrl2);
}
}
Add your comment