Steve Chambers Steve Chambers - 1 year ago 78
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) {
line = bufferedReader.readLine();
response = responseBuilder.toString();

But appending
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 Source

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 = > 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download