~/ learn/ comp-348/ cards/ Parsing the request line and mapping a path — safely
1 of 5

Split the request line, tolerating the two-token form

Split the request line, tolerating the two-token form

Answer

String[] tokens = requestLine.trim().split("\\s+"); if (tokens.length < 2) { sendError(out, "400 Bad Request"); return; } String method = tokens[0]; String target = new URI(tokens[1]).getPath(); String version = tokens.length > 2 ? tokens[2] : "";

`trim()` first, so a leading space cannot produce an empty token zero. `\\s+` splits on runs of whitespace rather than one space. `version` defaults to the empty string, which later fails the `startsWith("HTTP/")` test and correctly suppresses the header for an HTTP/0.9 client.

Harold 4e ch9 §A Full-Fledged HTTP Server

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/de1f3823-7c7b-4f21-ad67-17a37fd304ce/flashcard utf-8 LF