1. import java.io.IOException;
  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import java.net.URLConnection;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class WebFormArchiver {
  8. private static final String ARCHIVE_FILE = "form_archive.txt"; // File to store form data
  9. public static void archiveFormData(String formUrl) {
  10. try {
  11. URL url = new URL(formUrl);
  12. URLConnection connection = url.openConnection();
  13. connection.setDoOutput(true);
  14. // Get form data as a string
  15. String formData = getFormDataAsString(url);
  16. // Append data to the archive file
  17. appendFormDataToArchive(formData);
  18. } catch (MalformedURLException e) {
  19. System.err.println("Error: Invalid URL - " + formUrl);
  20. // Log the error or handle it appropriately
  21. } catch (IOException e) {
  22. System.err.println("Error: Could not access URL - " + formUrl);
  23. // Log the error or handle it appropriately
  24. } catch (Exception e) {
  25. System.err.println("An unexpected error occurred: " + e.getMessage());
  26. //Log the error or handle it appropriately
  27. }
  28. }
  29. private static String getFormDataAsString(URL url) throws IOException {
  30. // Send a POST request to the URL
  31. try (java.io.OutputStream outputStream = url.getOutputStream()) {
  32. outputStream.write(getFormDataBytes(new HashMap<>()));
  33. }
  34. // Read the response from the server
  35. java.io.BufferedReader reader = new java.io.BufferedReader(url.openStream(), java.nio.charset.StandardCharsets.UTF_8);
  36. return reader.ReadToEnd();
  37. }
  38. private static byte[] getFormDataBytes(Map<String, String> formData) {
  39. StringBuilder sb = new StringBuilder();
  40. for (Map.Entry<String, String> entry : formData.entrySet()) {
  41. sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
  42. }
  43. String formString = sb.toString();
  44. return formString.getBytes(java.nio.charset.StandardCharsets.UTF_8);
  45. }
  46. private static void appendFormDataToArchive(String formData) {
  47. try {
  48. java.io.FileWriter writer = new java.io.FileWriter(ARCHIVE_FILE, formData);
  49. writer.append("\n"); // Add a newline between form data entries
  50. writer.close();
  51. } catch (IOException e) {
  52. System.err.println("Error: Could not write to archive file - " + e.getMessage());
  53. //Log the error or handle it appropriately
  54. }
  55. }
  56. public static void main(String[] args) {
  57. // Example usage
  58. String formUrl1 = "https://www.example.com/form1";
  59. String formUrl2 = "https://www.example.com/form2";
  60. archiveFormData(formUrl1);
  61. archiveFormData(formUrl2);
  62. }
  63. }

Add your comment