【问题标题】:Android : Getting a Bitmap from a url connection (graph.facebook.com) that redirects to another urlAndroid:从重定向到另一个 url 的 url 连接 (graph.facebook.com) 获取位图
【发布时间】:2014-05-20 14:58:27
【问题描述】:

我已尽一切努力获取一个 url,我可以在其中获取 facebook 用户的个人资料图片。

现在剩下的唯一问题是将该图像转换为位图对象。

因为,http://graph.facebook.com 现在首先将连接(正如我们在 url 中看到的)重定向到 https://fbcdn-profile-a.akamaihd.net/...(类似这样)。

所以,我想问一下如何从 url 获取位图:http://graph.facebook.com/... 重定向到https://fbcdn-profile-a.akamaihd.net/...

【问题讨论】:

  • 你不应该加一个facebook标签吗?
  • @hiphopdroid 我认为将其通用化会更合适。因为url重定向不仅仅在这种情况下。

标签: android facebook facebook-graph-api bitmap url-redirection


【解决方案1】:

您说得对,http://graph.facebook.com 首先将连接重定向(正如我们在 url 中看到的那样)到 https://fbcdn-profile-a.akamaihd.net/,但是 -

当原始协议和重定向协议相同时,自动重定向会自动工作。

因此,如果您尝试从 https 而不是 http 加载图像:“https://graph.facebook.com/USER_ID/picture”;由于图像的 url 是“https://fbcdn-profile-a.akamaihd.net/....”,BitmapFactory.decodeStream 将再次为您获取位图。

这是代码-

URL imgUrl = new URL("https://graph.facebook.com/{user-id}/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap  bitmap = BitmapFactory.decodeStream(in);

希望对您有所帮助。祝你好运。

【讨论】:

  • 很抱歉回复晚了,但我真的很忙于其他工作,我无法再次检查这个问题。我还没有尝试过你的代码(如果它打扰了你,我真的很抱歉)。我会在尝试您的代码后尽快回复您。
  • 对不起,又迟到了,最近几天我什至没有时间好好睡觉。
  • 我试过你的方法,没有任何问题。感谢您分享您的知识。
  • @Sahil Mittal 我收到下一个错误:“android.os.NetworkOnMainThreadException”。您是否将此代码放入 AsyncTask 中?谢谢
【解决方案2】:

更新:Sahil Mittal 给出的方法非常有效,我一定会要求你们使用他的方法。

至于我在此期间使用的方法,您可以阅读此答案。

不知道Sahil Mittal给出的方法是否有效。

我没有尝试过,但我使用了另一个似乎对我有用的代码段。

但无论它是否有效,我都会在我尝试后立即回复。

Bitmap getUserBitmap(String username){


        HttpGet httpRequest = null;

        Bitmap userbmp = null;

        try {
            URL url = new URL("http://graph.facebook.com/" + username + "/picture?type=small");

            httpRequest = new HttpGet(url.toURI());

            HttpClient httpclient = new DefaultHttpClient();

            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

            HttpEntity entity = response.getEntity();

            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);

            InputStream instream = bufHttpEntity.getContent();

            userbmp = BitmapFactory.decodeStream(instream);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        userbmp = getRoundedShape(userbmp); // function call to make the image round
        return (userbmp);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2013-05-28
    • 2016-01-10
    • 2013-11-02
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多