Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse HTTP headers from HTTP request String using no 3rd party libs (Core Java)

Tags:

java

http

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

like image 560
RandomUser Avatar asked Aug 16 '12 14:08

RandomUser


2 Answers

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.

like image 60
parsifal Avatar answered Sep 30 '22 07:09

parsifal


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.

like image 45
Renato Avatar answered Sep 30 '22 08:09

Renato