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 = inputStream.read()));
        if ((char) charRead == '\r') {            // if we've got a '\r'
            sb.append((char) inputStream.read()); // then write '\n'
            charRead = inputStream.read();        // read the next char;
            if (charRead == '\r') {                  // if it's another '\r'
                sb.append((char) inputStream.read());// write the '\n'
                break;
            } 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.