Download image from url in Android only if

I use BitmapFactory.decodeStreamto download images from a url in Android. I only want to upload images below a certain size, and currently I'm using getContentLengthto check this out.

However, I was told that it getContentLengthdoes not always provide the file size, and in these cases I would like to stop the download as soon as I find out that the file is too large. What is the right way to do this?

Here is my current code. I am currently returning null if it getContentLengthdoes not give an answer.

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 >= 0 && (maxLength == 0 || contentLength < maxLength))) {
    InputStream is = bufHttpEntity.getContent();
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    return new BitmapDrawable(bitmap);
} else {
    return null;
}
+3
source share
3 answers

HttpHead HEAD, GET, . , GET .

HEAD- , . -, .

UPDATE , . , , BitmapFactory.

InputStream is = bufHttpEntity.getContent();
ByteArrayOutputStream bytes = ByteArrayOutputStream();
byte[] buffer = new byte[128];
int read;
int totalRead = 0;
while ((read = is.read(buffer)) > 0) {
   totalRead += read;
   if (totalRead > TOO_BIG) {
     // abort download. close connection
     return null;
   }
   bytes.write(buffer, 0 read);
}

, consumeContent() , HttpClient .

0

1. . ,

HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();  
int length=connection.getContentLength(); 

if(length<max){  
  InputStream is = connection.getInputStream();  
  BitmapFactory.decodeStream(is,null,null);
}

, -1 . , . . , HttpURLConnection , . , . , HttpClient .

2. . OutOfMemory durung, Bitmap. inSampleSize, . , . ListView ListView. ListView. . , .

+2

Source: https://habr.com/ru/post/1756410/


All Articles