【发布时间】:2010-07-25 10:56:02
【问题描述】:
我正在使用BitmapFactory.decodeStream 从 Android 中的 url 加载图像。我只想下载一定大小以下的图像,我目前正在使用getContentLength 来检查这一点。
但是,有人告诉我getContentLength 并不总是提供文件的大小,在这种情况下,我想在知道文件太大后立即停止下载。这样做的正确方法是什么?
这是我当前的代码。如果getContentLength 没有提供答案,我目前返回 null。
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;
}
【问题讨论】:
标签: android url bitmap httpclient httprequest