import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
public class HeaderStripper {
public static Map<String, String> stripMetadataHeaders(String request) {
Map<String, String> cleanedHeaders = new HashMap<>();
if (request == null || request.isEmpty()) {
return cleanedHeaders; // Handle null or empty request
}
String[] lines = request.split("\r\n"); // Split into lines
for (String line : lines) {
if (line.startsWith("Content-Type:")) {
continue; // Skip Content-Type header
}
if (line.startsWith("Transfer-Encoding:")) {
continue; // Skip Transfer-Encoding header
}
if (line.startsWith("Connection:")) {
continue; // Skip Connection header
}
if (line.startsWith("Upgrade:")) {
continue; // Skip Upgrade header
}
if (line.startsWith("Proxy-Connection:")) {
continue; // Skip Proxy-Connection header
}
if (line.startsWith("Host:")) {
continue; // Skip Host header
}
if (line.startsWith("Authorization:")) {
continue; // Skip Authorization header
}
if (line.startsWith("Cookie:")) {
continue; // Skip Cookie header
}
// Further filtering for metadata-related headers. Add more as needed.
if (line.startsWith("X-Powered-By:")) {
continue; // Skip X-Powered-By header
}
if (line.startsWith("Server:")) {
continue; // Skip Server header
}
if (line.startsWith("Date:")) {
continue; // Skip Date header
}
if(line.startsWith("Via:")) {
continue; // Skip Via header
}
//If we reach here, it's a potentially useful header.
String header = line.substring(0).trim();
String value = "";
if (line.contains(":") && line.indexOf(":") > 0) {
value = line.substring(line.indexOf(":") + 1).trim();
}
if(!header.isEmpty()){
cleanedHeaders.put(header, value);
}
}
return cleanedHeaders;
}
public static void main(String[] args) throws IOException {
String request = "GET / HTTP/1.1\r\n" +
"Host: example.com\r\n" +
"User-Agent: MyClient\r\n" +
"X-Powered-By: PHP/7.4\r\n" +
"Date: Tue, 26 Oct 2023 10:00:00 GMT\r\n" +
"Server: Apache/2.4.41\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Content-Type: application/json\r\n" +
"Authorization: Bearer some_token\r\n" +
"\r\n";
Map<String, String> cleaned = stripMetadataHeaders(request);
for (Map.Entry<String, String> entry : cleaned.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Add your comment