如何准确识别HTTP请求头结束位置?Java开发场景的技术疑问
Great question—this is a common point of confusion when dealing with HTTP request parsing, especially with multipart payloads. Let's break this down step by step:
To start, the HTTP/1.x specification defines a request's structure as:
Request line (e.g.,
POST /hello:hello HTTP/1.1)
Zero or more header fields (each inKey: Valueformat)
A blank line (CRLF sequence)
Request body (if present)
That blank line you're seeing in your example is indeed the end of the request headers. The content after it belongs to the request body, not the headers. The boundary parameter in the Content-Type header is used to split different parts within the request body (like form fields or uploaded files)—it has nothing to do with where the headers end.
If relying on Content-Length feels inefficient or isn't feasible (e.g., the header is missing or tampered with), here are standard, reliable approaches:
Chunked Transfer Encoding (
Transfer-Encoding: chunked)
When this header is present, the request body is sent as a series of chunks. Each chunk follows this format:[Hexadecimal chunk length]\r\n [Chunk content]\r\nThe request body ends with a chunk of length
0(marked by0\r\n\r\n). You'll need to parse each chunk sequentially until you hit this terminating chunk.Multipart Boundary Parsing
For multipart requests, even withoutContent-Length, you can extract theboundaryvalue from theContent-Typeheader (e.g.,--------------------------276559868742390689469124in your example). Then scan the request body for the boundary markers:--[boundary]starts a new part--[boundary]--signals the end of the entire request body
Again, remember this is for parsing the body—headers still end at the blank line.
Connection Closure (
Connection: close)
If the request includesConnection: close, the client will close the TCP connection once the entire request is sent. You can treat the end of the connection as the end of the request. However, this is inefficient for persistent connections and should be a fallback, not a primary approach.
In Java, you can use a BufferedReader to read lines until you hit a blank line (an empty string after trimming, or a line that's just \r\n). That's your signal the headers are done. Then:
- If
Transfer-Encoding: chunkedis present, switch to reading chunks by parsing the hex length first, then reading that many bytes. - If it's a multipart request, extract the boundary, then read the body byte stream to find the boundary markers.
- If
Content-Lengthis available, read exactly that number of bytes for the body.
Just be mindful of line ending handling: the HTTP spec requires \r\n (CRLF) for line breaks, but some clients might send just \n—your parser should handle both cases gracefully.
内容的提问来源于stack exchange,提问作者Kavzor

