title: Load image from url in Android, only if small
body: <p>I'm using <code>BitmapFactory.decodeStream</code> to load an image from a url in Android. I want to only download images below a certain size, and I'm currently using <code>getContentLength</code> to check this. </p>
  
  <p>However, I'm told that <code>getContentLength</code> doesn't always provide the size of the file, and in those cases I would like to stop the download as soon as I know that the file is too big. What is the right way to do this?</p>
  
  <p>Here is my current code. I currently return null if <code>getContentLength</code> doesn't provide an answer.</p>
  
  <pre><code>HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
  HttpClient httpClient = new DefaultHttpClient();
  HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
  HttpEntity entity = response.getEntity();
  BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
  final long contentLength = bufHttpEntity.getContentLength();
  if ((contentLength &gt;= 0 &amp;&amp; (maxLength == 0 || contentLength &lt; maxLength))) {
      InputStream is = bufHttpEntity.getContent();
      Bitmap bitmap = BitmapFactory.decodeStream(is);
      return new BitmapDrawable(bitmap);
  } else {
      return null;
  }
  </code></pre>