1. import java.io.IOException;
  2. import java.net.Socket;
  3. import java.net.SocketTimeoutException;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class HeaderStripper {
  7. public static Map<String, String> stripMetadataHeaders(String request) {
  8. Map<String, String> cleanedHeaders = new HashMap<>();
  9. if (request == null || request.isEmpty()) {
  10. return cleanedHeaders; // Handle null or empty request
  11. }
  12. String[] lines = request.split("\r\n"); // Split into lines
  13. for (String line : lines) {
  14. if (line.startsWith("Content-Type:")) {
  15. continue; // Skip Content-Type header
  16. }
  17. if (line.startsWith("Transfer-Encoding:")) {
  18. continue; // Skip Transfer-Encoding header
  19. }
  20. if (line.startsWith("Connection:")) {
  21. continue; // Skip Connection header
  22. }
  23. if (line.startsWith("Upgrade:")) {
  24. continue; // Skip Upgrade header
  25. }
  26. if (line.startsWith("Proxy-Connection:")) {
  27. continue; // Skip Proxy-Connection header
  28. }
  29. if (line.startsWith("Host:")) {
  30. continue; // Skip Host header
  31. }
  32. if (line.startsWith("Authorization:")) {
  33. continue; // Skip Authorization header
  34. }
  35. if (line.startsWith("Cookie:")) {
  36. continue; // Skip Cookie header
  37. }
  38. // Further filtering for metadata-related headers. Add more as needed.
  39. if (line.startsWith("X-Powered-By:")) {
  40. continue; // Skip X-Powered-By header
  41. }
  42. if (line.startsWith("Server:")) {
  43. continue; // Skip Server header
  44. }
  45. if (line.startsWith("Date:")) {
  46. continue; // Skip Date header
  47. }
  48. if(line.startsWith("Via:")) {
  49. continue; // Skip Via header
  50. }
  51. //If we reach here, it's a potentially useful header.
  52. String header = line.substring(0).trim();
  53. String value = "";
  54. if (line.contains(":") && line.indexOf(":") > 0) {
  55. value = line.substring(line.indexOf(":") + 1).trim();
  56. }
  57. if(!header.isEmpty()){
  58. cleanedHeaders.put(header, value);
  59. }
  60. }
  61. return cleanedHeaders;
  62. }
  63. public static void main(String[] args) throws IOException {
  64. String request = "GET / HTTP/1.1\r\n" +
  65. "Host: example.com\r\n" +
  66. "User-Agent: MyClient\r\n" +
  67. "X-Powered-By: PHP/7.4\r\n" +
  68. "Date: Tue, 26 Oct 2023 10:00:00 GMT\r\n" +
  69. "Server: Apache/2.4.41\r\n" +
  70. "Connection: close\r\n" +
  71. "Transfer-Encoding: chunked\r\n" +
  72. "Content-Type: application/json\r\n" +
  73. "Authorization: Bearer some_token\r\n" +
  74. "\r\n";
  75. Map<String, String> cleaned = stripMetadataHeaders(request);
  76. for (Map.Entry<String, String> entry : cleaned.entrySet()) {
  77. System.out.println(entry.getKey() + ": " + entry.getValue());
  78. }
  79. }
  80. }

Add your comment