简体   繁体   中英

How to get facebook profile picture of user in facebook SDK Android

I used facebook 3.6 sdk . i want to get profile picture from graph user , last time i got image but now it returns null Bitmap.

I used following code

private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (session.isOpened()) {
            Request.newMeRequest(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        try {
                            URL imgUrl = new URL("http://graph.facebook.com/"
                                    + user.getId() + "/picture?type=large");

                            InputStream in = (InputStream) imgUrl.getContent();
                            Bitmap  bitmap = BitmapFactory.decodeStream(in);
                            //Bitmap bitmap = BitmapFactory.decodeStream(imgUrl      // tried this also
                            //.openConnection().getInputStream());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).executeAsync();
        }
    }

When i use direct link then it works.

imgUrl = new URL("https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-ash3/t39.2365-6/851558_160351450817973_1678868765_n.png");

i refered this also Graph API Reference

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

So, 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/ ...."

Then BitmapFactory.decodeStream shall work again.

Try this code,

try {
        URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
        Bitmap bmp = null;
        try {
                bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
                profile_pic.setImageBitmap(bmp);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

here profile_pic is your ImageView replace it with your ImageView Name.

Edit

Session.openActiveSession(this, true, new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (session.isOpened()) {
                // make request to the /me API
                Request.executeMeRequestAsync(session,
                        new Request.GraphUserCallback() {
                            @Override
                            public void onCompleted(GraphUser user,
                                    Response response) {
                                if (user != null) {
                                   try {
    URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
    Bitmap bmp = null;
    try {
            bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
            profile_pic.setImageBitmap(bmp);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
                                }
                            }
                        });
            } else {
                Toast.makeText(getApplicationContext(), "Error...",
                        Toast.LENGTH_LONG);
            }
        }
    });

Try this code

public static String getProfilePicture() {

    String stringURL = null;
    try {
        stringURL = "http://graph.facebook.com/" + URLEncoder.encode(DataStorage.getFB_USER_ID(), "UTF-8") + "?fields=" + URLEncoder.encode("picture", "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    LogUtil.log(TAG, "getProfilePicture final url is : "+stringURL);

    JSONObject jsonObject = null;
    String response = "";

    try {

        HttpGet get = new HttpGet(stringURL);
        get.setHeader("Content-Type", "text/plain; charset=utf-8");
        get.setHeader("Expect", "100-continue");

        HttpResponse resp = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            resp = httpClient.execute(get);
        } catch (Exception e) {
            e.printStackTrace();

        } 
        // get the response from the server and store it in result
        DataInputStream dataIn = null;
        try {
            //              dataIn = new DataInputStream(connection.getInputStream());
            if (resp != null) {
                dataIn = new DataInputStream((resp.getEntity().getContent()));
            }
        }catch (Exception e) {
            e.printStackTrace();

        } 

        if(dataIn != null){
            String inputLine;
            while ((inputLine = dataIn.readLine()) != null) {
                response += inputLine;
            }

            if(Constant.DEBUG)  Log.d(TAG,"final response is  : "+response);

            if(response != null && !(response.trim().equals(""))) {
                jsonObject = new JSONObject(response);
            }

            dataIn.close();
        }

    } catch (Exception e) {
        e.printStackTrace();

    } 

    String profilePicture = "";
    try{
        if(jsonObject != null){
            JSONObject jsonPicture = jsonObject.getJSONObject("picture");
            if(jsonPicture != null){
                JSONObject jsonData = jsonPicture.getJSONObject("data");
                if(jsonData != null){
                    profilePicture = jsonData.getString("url");
                }
            }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

    LogUtil.log(TAG, "user fb profile picture url is : "+profilePicture);
    return profilePicture;
}

I tried to use redirect page " https://fbcdn-profile-a.akamaihd.net/ " + USERID + "/picture?type=large" but it didn't work.

It seems that now facebook redirect you to a different page that we cannot guess. Kind of random variables in URL.

So try below method to get the new redirect page provided by facebook.

private String getProfileGif(String userId) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter("http.protocol.handle-redirects", false);
    HttpGet pageToRequest = new HttpGet("http://graph.facebook.com/" + userId + "/picture?type=large");
    pageToRequest.setParams(httpParams);

    AndroidHttpClient httpClient = AndroidHttpClient
            .newInstance("Android");
    HttpMessage httpResponse = httpClient.execute(pageToRequest);
    Header header = httpResponse.getFirstHeader("location");

    if(header != null){
        return(header.getValue());
    }

    return "";
}

This is gonna return you the real gif URL (final URL).

After that, use this new URL to parse your bitmap.

Change from:

URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");

to

URL image_value = new URL(getProfileGif(user.getId());
Bitmap bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());

PS: Dont execute getProfileGif or any URL request in main thread.

Let me know your results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM