code: private static int readFully(InputStream in, ByteArrayOutputStream bout,
              int length) throws IOException {
          int read = 0;
          byte[] buffer = new byte[2048];
          while (length > 0) {
              int n = in.read(buffer, 0, length<2048?length:2048);
              if (n <= 0) {
                  break;
              }
              bout.write(buffer, 0, n);
              read += n;
              length -= n;
          }
          return read;
      }
docs: Read from the stream until length bytes have been read or EOF has
  been reached. Return the number of bytes actually read.