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

8
我将使用 Facebook 3.6 SDK。我想要从 Graph 用户获取个人资料图片,上次我得到了图片,但现在它返回空的 Bitmap。
以下是我的代码:
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();
        }
    }

当我使用直接链接时,它可以正常工作。
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

4个回答

25

感谢您对重定向的揭示。 - Mushtaq Jameel
我认为在URL中加入&redirect=false可以防止重定向,不是吗? - theapache64

3

尝试这段代码:

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

这里的profile_pic是你的ImageView,请将其替换为你的ImageView名称。
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);
            }
        }
    });

位图再次返回 _null_。 - Tulsiram Rathod
我尝试了并获得了正确的链接。当我在浏览器中点击此链接时,图像会加载,但是通过代码Bitmap返回null。 - Tulsiram Rathod

1
尝试这段代码。
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;
}

从这个 URL 中获取了个人头像,但是图片质量不太好。 - Tulsiram Rathod
@TulsiramRathod 你能分享图片的URL吗? - Yuvaraja
请检查此链接:https://m.ak.fbcdn.net/profile.ak/hprofile-ak-prn2/t5.0-1/203169_100000114511793_1329215586_q.jpg - Tulsiram Rathod

-1

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

现在似乎Facebook会将您重定向到我们无法猜测的不同页面。URL中有一些随机变量。

因此,请尝试以下方法以获取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 "";
}

这将返回真实的 gif URL(最终 URL)。

然后,使用此新 URL 解析您的位图。

改为:

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

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

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

让我知道你的结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接