Fork me on GitHub

Java: Parse HTTP headers from an InputStream

After using this method, you'd be able to access the HTTP body data by reading the rest of the InputStream.

public static Map<String, String> parseHTTPHeaders(InputStream inputStream)
        throws IOException {
    int charRead;
    StringBuffer sb = new StringBuffer();
    while (true) {
        sb.append((char) (charRead =;
        if ((char) charRead == '\r') {            // if we've got a '\r'
            sb.append((char); // then write '\n'
            charRead =;        // read the next char;
            if (charRead == '\r') {                  // if it's another '\r'
                sb.append((char);// write the '\n'
            } else {
                sb.append((char) charRead);

    String[] headersArray = sb.toString().split("\r\n");
    Map<String, String> headers = new HashMap<>();
    for (int i = 1; i < headersArray.length - 1; i++) {
        headers.put(headersArray[i].split(": ")[0],
                headersArray[i].split(": ")[1]);

    return headers;

I wrote this method because using a BufferedReader leads to undefined behavior; the read data is different each single time.