From 21bd3e192aa5015aee4d05abf39359fc39aad6df Mon Sep 17 00:00:00 2001 From: Yifeng Jin Date: Wed, 13 Jun 2012 11:11:34 -0700 Subject: [PATCH] Solve image downloading issue caused by getContentLength(). According to Android documentation "By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream()." --- .../images/remote/RemoteImageLoaderJob.java | 43 ++++++------------- 1 file changed, 14 insertions(+), 29 deletions(-) diff --git a/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderJob.java b/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderJob.java index 733993c..0ccdf9c 100644 --- a/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderJob.java +++ b/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderJob.java @@ -89,44 +89,29 @@ protected byte[] retrieveImageData() throws IOException { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - // determine the image size and allocate a buffer - int fileSize = connection.getContentLength(); - Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")"); + Log.d(LOG_TAG, "fetching image " + imageUrl); BufferedInputStream istream = new BufferedInputStream(connection.getInputStream()); - - try { - if (fileSize <= 0) { - Log.w(LOG_TAG, - "Server did not set a Content-Length header, will default to buffer size of " - + defaultBufferSize + " bytes"); - ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize); - byte[] buffer = new byte[defaultBufferSize]; - int bytesRead = 0; - while (bytesRead != -1) { - bytesRead = istream.read(buffer, 0, defaultBufferSize); - if (bytesRead > 0) - buf.write(buffer, 0, bytesRead); - } - return buf.toByteArray(); - } else { - byte[] imageData = new byte[fileSize]; - - int bytesRead = 0; - int offset = 0; - while (bytesRead != -1 && offset < fileSize) { - bytesRead = istream.read(imageData, offset, fileSize - offset); - offset += bytesRead; - } - return imageData; - } + byte[] imageData = null; + ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize);; + try { + byte[] buffer = new byte[defaultBufferSize]; + int bytesRead = 0; + do { + bytesRead = istream.read(buffer, 0, defaultBufferSize); + if (bytesRead > 0) + buf.write(buffer, 0, bytesRead); + } while (bytesRead != -1); + imageData = buf.toByteArray(); } finally { // clean up try { istream.close(); + buf.close(); connection.disconnect(); } catch (Exception ignore) { } } + return imageData; } protected void notifyImageLoaded(String url, Bitmap bitmap) {