I'm building an HTTP server and parsing request headers. My current code fails when the Host header includes a port number because I'm splitting on :.
Current Code:
String[] header = line.split(":");
String key = header[0].trim();
String value = header[1].trim();
if (key.equals("Host")) {
value = value + ":" + header[2]; // ArrayIndexOutOfBoundsException!
}
Problem:
Works for
Host: example.com:8080Fails for
Host: example.com(no port)
Question:
What's the best way to rejoin header values that may contain colons?
What I've tried:
Checking
header.lengthbut feels clunkyUsing
indexOf(':')instead ofsplit()
Which approach is more robust for HTTP header parsing?