Android : Getting a Bitmap from a url connection (

2019-02-18 22:56发布

I have done everything to get a url where i can get the profile pic of a facebook user.

The only problem left now is to get that image into a bitmap object.

Since, http://graph.facebook.com now redirects the connection first (as we can see in the url) to https://fbcdn-profile-a.akamaihd.net/... (something like this).

So, i wanted to ask as to how can i get the bitmap from the url : http://graph.facebook.com/... that redirects to https://fbcdn-profile-a.akamaihd.net/...

2条回答
一夜七次
2楼-- · 2019-02-18 23:11

Update : The method given by Sahil Mittal works absolutely fine and i would definitely ask you guys to use his method.

As for the method I used in the meantime you can read this answer.

I dont know whether the method given by Sahil Mittal works or not.

I havent tried that but i used another code segment which seems to work for me.

But i will get back whether it works or not as soon as i try it.

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);
    }
查看更多
聊天终结者
3楼-- · 2019-02-18 23:25

You are right in saying that http://graph.facebook.com redirects the connection first (as we can see in the url) to https://fbcdn-profile-a.akamaihd.net/, but-

auto redirection works automatically when original and redirected protocols are same.

So, if you try to load images from https instead of http : "https://graph.facebook.com/USER_ID/picture"; since image's url is "https://fbcdn-profile-a.akamaihd.net/....", BitmapFactory.decodeStream shall work again to get you the bitmap.

Here's the code-

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

Hope that helps. Good luck.

查看更多
登录 后发表回答