Tuesday, March 6, 2012

Converting an inputStream to String in utf-8

Sometimes we need to check the response of the http request by converting the stream to a string.  A simple method with which  we can do it in UTF-8 format  is  follows.
public static String readStream(InputStream in) throws Exception {

  if(in == null){
     return "";
  }

  int ch;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  while ((ch = in.read()) != -1) {
   bos.write(ch);
  }
  in.close();
  return new String(bos.toByteArray(), "UTF-8");

}

No comments:

Post a Comment