Read buffer completely when using Android/Java’s InputStream

When you use InputStream to read into a byte [] buffer, make sure you read all the bytes. The in.read(byte [] buffer, int offset, int byteCount) method makes no guarantee that it will read byteCount bytes in the first read. To read all bytes:

 

private byte [] readStream(HttpURLConnection urlConnection) throws IOException {
    urlConnection.setDoInput(true);
    int contentLength = urlConnection.getContentLength();
    byte [] buffer = new byte[contentLength];

    InputStream in = urlConnection.getInputStream();
    int bytesRead = 0;
    int offset = 0;

    while ((bytesRead = in.read(buffer, offset, contentLength - offset)) >= 0) {
        offset += bytesRead;
    }

    return buffer;
}