This method gets the response body of a stream in every detail. I had an experience retrieving the contents of an HTML page and the output was messy. The line breaks were not correct as in the original source. To fix this, use the method below. It returns the response body as a String and its output is the same as when you do a view source code of the HTML page.


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;

public static String getResponseBodyFromStream(InputStream is) {
  String str = "";
  try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[128];
    int size = 0;

    while ((size = is.read(buffer)) > 0) {
      baos.write(buffer, 0, size);
    }
    str = new String(baos.toByteArray());
  } catch (IOException ioe) { }
  return str;
}

Related Posts Plugin for WordPress, Blogger...