我正在使用以下 void 方法从 URL 获取位图图像:
public static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
我用这种方法提供的最常见的 URL 是:http: //graph.facebook.com/+FACEBOOK_USER_ID+/picture,但是这个 URL 重定向到http://profile.ak.fbcdn.net/static-ak/rsrc。 php/v2/y9/r/xxxxx.gif。这就是为什么我没有得到位图图像,我得到的是与 302 重定向相关的错误。如何处理重定向的 URL,并获取位图文件?