如何在Facebook SDK Android中获取用户的Facebook个人资料图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22907742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:33:04  来源:igfitidea点击:

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

androidfacebookfacebook-graph-apifacebook-android-sdk

提问by Tulsiram Rathod

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.

我使用了 facebook 3.6 sdk 。我想从图形用户那里获取个人资料图片,上次我获取图像但现在它返回空位图。

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

我也提到了这个图形 API 参考

回答by Sahil Mittal

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

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

So, try to load images from httpsinstead of http: "https://graph.facebook.com/USER_ID/picture"; since image's url is "https://fbcdn-profile-a.akamaihd.net/...."

因此,尝试从https而不是http加载图像:“ https://graph.facebook.com/USER_ID/picture”;因为图片的网址是“ https://fbcdn-profile-a.akamaihd.net/....”

Then BitmapFactory.decodeStreamshall work again.

然后BitmapFactory.decodeStream将再次工作。

回答by InnocentKiller

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_picis your ImageViewreplace it with your ImageViewName.

profile_pic是你ImageView用你的ImageView名字替换它。

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);
            }
        }
    });

回答by Yuvaraja

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;
}

回答by febaisi

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

我尝试使用重定向页面“ https://fbcdn-profile-a.akamaihd.net/” + USERID + “/picture?type=large” 但它没有用。

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

现在 facebook 似乎将您重定向到我们无法猜测的其他页面。URL 中的一种随机变量。

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

所以尝试下面的方法来获取 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).

这将返回您真正的 gif 网址(最终网址)。

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

之后,使用这个新 URL 来解析您的位图。

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.

PS:不要在主线程中执行 getProfileGif 或任何 URL 请求。

Let me know your results.

让我知道你的结果。