Given an HTTP request header, does anyone have suggestions or know of existing code to properly parse the header? I am trying to do this with Core Java only, no third party libs
Edit:
Trying to find key fields from this String for example:
GET / HTTP/1.1User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15Host: localhost:9000Accept: /
Want to parse out the Method and method
Start by reading and understanding the HTTP specification.
The request line and headers are separated by CR LF sequences (bytes with decimal value 13 and 10), so you can read the stream and separate out each line. I believe that the headers must be encoded in US-ASCII, so you can simply convert bytes to characters and append to a StringBuilder
(but check the spec: it may allow ISO-8859-1 or another encoding).
The end of the headers is signified by CR LF CR LF.
I wrote a library, RawHTTP, whose only purpose is to parse HTTP messages (requests and responses).
If you don't want to use a library, you could copy the source into your own code base, starting form this: https://github.com/renatoathaydes/rawhttp/blob/a6588b116a4008e5b5840d4eb66374c0357b726d/rawhttp-core/src/main/java/com/athaydes/rawhttp/core/RawHttp.java#L52
This will split the lines of the HTTP message all the way to the end of the metadata sections (start-line + headers).
With the list of metadata lines at hand, you can then call the parseHeaders
method, which will create the headers for you. You can easily adapt that to just return a Map<String, List<String>>
to avoid having to also import the header classes.
That said... RawHTTP has no dependencies, so I would just use it instead :) but up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With