Steve Chambers Steve Chambers - 1 month ago 6
Java Question

How to read a textual HTTP response into a String exactly as-is?

The following code uses BufferedReader to read from an HTTP response stream:

final StringBuilder responseBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
responseBuilder.append(line);
responseBuilder.append('\n');
line = bufferedReader.readLine();
}
response = responseBuilder.toString();


But appending
'\n'
to each line seems a bit flawed. I want to return the HTTP response exactly as-is so what if it doesn't have a return character after the last line? One would get added anyway using the code above - is there a better way?

Answer

I want to return the HTTP response exactly as-is

Don't use readLine() then - it's as simple as that. I'd suggest using a StringWriter instead:

StringWriter writer = new StringWriter();
char[] buffer = new char[8192];
int charsRead;
while ((charsRead = bufferedReader.read(buffer)) > 0) {
    writer.write(buffer, 0, charsRead);
}
response = writer.toString();

Note that even this won't work if you get the encoding wrong. To preserve the exact HTTP response, you'd need to read (and write) it as a binary stream.