【问题标题】:Retrieving Bitmap from Redirected URL从重定向的 URL 中检索位图
【发布时间】:2012-07-26 16:32:04
【问题描述】:

我正在使用以下 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,并获取位图文件?

【问题讨论】:

    标签: android facebook-graph-api


    【解决方案1】:

    为什么不直接请求图片 URL 并直接获取呢?

    而不是https://graph.facebook.com/[object id]/picture

    请求 https://graph.facebook.com/[object id]?fields=picture

    【讨论】:

    • https://graph.facebook.com/[object id]?fields=picture 返回JSON。因此,我不会直接获取它,而是首先解析JSON 以获得确切的URL。不过建议不错! :)
    【解决方案2】:

    您需要在 URL 中附加 ?type=large 才能获取图片...

    例如,下面的代码显示了如何进入 imageview...

    ImageView 用户图片;

    userpicture=(ImageView)findViewById(R.id.userpicture);

    网址 img_value = null;

    img_value = 新的 URL("http://graph.facebook.com/"+id+"/picture?type=large");

    位图 mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());

    userpicture.setImageBitmap(mIcon1);

    尝试在 URL 中添加 ?type=large 并告诉我您的结果。

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 1970-01-01
      • 2014-01-16
      • 2013-08-09
      • 2014-01-15
      • 2014-05-02
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      相关资源
      最近更新 更多