code: public static int safeRead(final InputStream inputStream, final byte[] buffer) throws IOException {
          int readBytes = inputStream.read(buffer);
          if(readBytes == -1) {
              return -1;
          }
          if(readBytes < buffer.length) {
              int offset = readBytes;
              int left = buffer.length;
              left = left - readBytes;
              do {
                  try {
                      final int nr = inputStream.read(buffer, offset, left);
                      if (nr == -1) {
                          return nr;
                      }
                      offset += nr;
                      left -= nr;
                  } catch (InterruptedIOException exp) {
                      /* Ignore, just retry */
                  }
              } while (left > 0);
          }
          return buffer.length;
      }
docs: Read a number of bytes from the stream and store it in the buffer, and fix the problem with "incomplete" reads by
  doing another read if we don't have all of the data yet.
  
  @param inputStream the input stream to read from
  @param buffer      where to store the data
  @return the number of bytes read (should be == length if we didn't hit EOF)
  @throws java.io.IOException if an error occurs while reading the stream