Skip to content

How to read http headers synchronously using BufferedReader?

My problem is that BufferedReader#read() creates an infinite delay until the connection is terminated. As soon as it is interrupted, immediately BufferedReader produces the result. So, because of these delays, I cannot read the headers in sync with the page load.

Answer

BufferedReader is not the solution, as the name implies, it buffers data by N bytes or until end of stream (when socket is closed) “for the efficient reading of characters, arrays, and lines.” If your BufferedReader is just socket.getInputStream(), then use that.

int b = -1;
while ((b = socket.getInputStream().read()) != 1) {
    System.out.print((char)b);
}