PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

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

 October 30, 2022     bufferedreader, carriage-return, eof, java, readline     No comments   

Issue

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?


Solution

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.



Answered By - Jon Skeet
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing