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

时间:2014-04-07 08:54:18

标签: android facebook facebook-graph-api facebook-android-sdk

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

我使用了以下代码

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

我也提到了Graph API Reference

4 个答案:

答案 0 :(得分:25)

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

因此,请尝试从 https 而非 http 加载图片:" https://graph.facebook.com/USER_ID/picture&#34 ;;因为图片的网址是" https://fbcdn-profile-a.akamaihd.net/ ...."

然后BitmapFactory.decodeStream将再次运作。

答案 1 :(得分: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_picImageView用您的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);
            }
        }
    });

答案 2 :(得分: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;
}

答案 3 :(得分:-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 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());

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

让我知道你的结果。