1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.io.StringWriter;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class MetadataStripper {
  7. /**
  8. * Strips metadata from response headers.
  9. *
  10. * @param responseHeaders A map of response headers.
  11. * @param stripFlags A string containing flags to control stripping behavior.
  12. * Valid flags: "user-agent", "content-length", "date", "server", "cache-control", "transfer-encoding", "content-type", "location", "etag", "last-modified"
  13. * @return A map of stripped response headers. Returns an empty map if input is null.
  14. */
  15. public static Map<String, String> stripMetadata(Map<String, String> responseHeaders, String stripFlags) {
  16. if (responseHeaders == null) {
  17. return new HashMap<>();
  18. }
  19. Map<String, String> strippedHeaders = new HashMap<>();
  20. if (stripFlags == null || stripFlags.isEmpty()) {
  21. return responseHeaders; // No flags, return original headers
  22. }
  23. String[] flags = stripFlags.split(",");
  24. for (String flag : flags) {
  25. String trimmedFlag = flag.trim(); // remove leading/trailing whitespace
  26. if (trimmedFlag.equalsIgnoreCase("user-agent") || trimmedFlag.equalsIgnoreCase("content-length") || trimmedFlag.equalsIgnoreCase("date") || trimmedFlag.equalsIgnoreCase("server") || trimmedFlag.equalsIgnoreCase("cache-control") || trimmedFlag.equalsIgnoreCase("transfer-encoding") || trimmedFlag.equalsIgnoreCase("content-type") || trimmedFlag.equalsIgnoreCase("location") || trimmedFlag.equalsIgnoreCase("etag") || trimmedFlag.equalsIgnoreCase("last-modified")) {
  27. strippedHeaders.put(trimmedFlag, null); // Set value to null to effectively remove the header
  28. }
  29. }
  30. return strippedHeaders;
  31. }
  32. public static void main(String[] args) throws IOException {
  33. // Example Usage
  34. Map<String, String> headers = new HashMap<>();
  35. headers.put("User-Agent", "MyUserAgent");
  36. headers.put("Content-Length", "1234");
  37. headers.put("Date", "Thu, 26 Oct 2023 10:00:00 GMT");
  38. headers.put("Server", "Apache/2.4.41");
  39. headers.put("Cache-Control", "no-cache");
  40. headers.put("Content-Type", "text/html");
  41. String stripFlags = "user-agent,content-length,date";
  42. Map<String, String> stripped = stripMetadata(headers, stripFlags);
  43. StringWriter sw = new StringWriter();
  44. PrintWriter pw = new PrintWriter(sw);
  45. for (Map.Entry<String, String> entry : stripped.entrySet()) {
  46. pw.println(entry.getKey() + ": " + entry.getValue());
  47. }
  48. System.out.println(sw.toString());
  49. }
  50. }

Add your comment