【问题标题】:How to get facebook profile picture of user in facebook SDK Android如何在 facebook SDK Android 中获取用户的 facebook 个人资料图片
【发布时间】:2014-04-07 08:54:18
【问题描述】:

我使用了 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

【问题讨论】:

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


    【解决方案1】:

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

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

    然后BitmapFactory.decodeStream 将再次工作。

    【讨论】:

    • 感谢您对重定向的披露。
    • 我认为通过将&redirect=false 放在 url 中可以防止重定向,不是吗?
    【解决方案2】:

    试试这个代码,

    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
    • 我试过了,我得到了正确的链接。当我在浏览器中点击这个链接然后图像加载,但位图通过代码返回 null
    【解决方案3】:

    试试这个代码

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

    【讨论】:

    【解决方案4】:

    我尝试使用重定向页面“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());
    

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

    让我知道你的结果。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多