从Facebook Graph-API获取用户图像

20

我想在列表视图中显示用户的个人资料图片。 当我试图从安卓端调用Graph API检索图片时,总是收到以下错误信息。

java.io.IOException: Hostname <fbcdn-profile-a.akamaihd.net> was not verified
    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.getSecureSocket(HttpConnection.java:170)
    at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnection$HttpsEngine.connect(HttpsURLConnection.java:398)
    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.sendRequest(HttpURLConnection.java:1224)
    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.doRequestInternal(HttpURLConnection.java:1558)
    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.doRequest(HttpURLConnection.java:1551)
    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1052)
    at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnection.getInputStream(HttpsURLConnection.java:252)
    at com.facebook.android.Util.openUrl(Util.java:200)
    at com.facebook.android.Facebook.request(Facebook.java:559)

这是我使用的代码:

private static void retrieveProfilePicture(String userId) throws MalformedURLException, IOException{
        facebook = FacebookHelper.getInstance();
        Bundle bundle = new Bundle();
        bundle.putString(Facebook.TOKEN, facebook.getAccessToken());
        Object picture = facebook.request("/"+userId+"/picture", bundle, "GET");

当我在浏览器中进行相同的调用(https://graph.facebook.com//picture?access_token=),那么我会得到一个像这样的url返回的图像 https://fbcdn-profile-a.akamaihd.net/...

这个图像以什么格式交付给我?是带有指向图像的引用(url)的JSON吗?

7个回答

83
 ImageView user_picture;
 userpicture=(ImageView)findViewById(R.id.userpicture);
 URL img_value = null;
 img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
 Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
 userpicture.setImageBitmap(mIcon1);

其中ID是您的个人资料ID之一。

有关详细信息,请查看Graph API参考

............................


3
@FelipeConde 不需要任何访问令牌。您可以在任何浏览器上使用此URL,并查看它适用于任何个人资料ID。 - IncrediApp
2
@IncrediApp 你是对的。当使用“me”而不是用户ID时,只需要令牌。 - Felipe Conde
@Venky 我遇到了下一个错误:"android.os.NetworkOnMainThreadException"。你是否将此代码放在AsyncTask中?谢谢。 - KryNaC
是的,这段代码会阻塞主线程直到下载完成。非常糟糕,特别是如果您同时发出30个这样的请求。 - slinden77

16

我知道这个问题有点老,但现在有另一种简单获取用户图片的方法。

首先,在xml布局中使用:

<com.facebook.widget.ProfilePictureView
        android:id="@+id/userImage"
        android:layout_width="69dp"
        android:layout_height="69dp"
        android:layout_gravity="center_horizontal" />

然后在您的碎片或活动中,在方法onSessionStateChange中:

private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (state.isOpened()) {
            Log.i(TAG, "Logged in...");

            // Request user data and show the results
            Request.newMeRequest(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        //HERE: DISPLAY USER'S PICTURE
                        userPicture.setProfileId(user.getId());
                    }
                }
            }).executeAsync();

        } else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");

            userPicture.setProfileId(null);
        }
    }

希望这可以帮助到某人。我曾经面临同样的问题,找到了这篇帖子,但它是2011年的。如今(2013年),做事情的方式已经改变了。


6

您可以使用ProfilePictureView而不是ImageView来完成此操作:

<com.facebook.widget.ProfilePictureView
   android:id="@+id/friendProfilePicture"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center_horizontal"
   android:padding="5sp"
   facebook:preset_size="small" />

您可以将尺寸设置为小/正常/大/自定义。

然后在您的代码中,像这样设置用户Facebook ID:

ProfilePictureView profilePictureView;
profilePictureView = (ProfilePictureView) findViewById(R.id.friendProfilePicture);
profilePictureView.setProfileId(userId);

希望这有帮助。

迄今为止最简单的解决方案,但我认为该包已经移动到com.facebook.login.widget.ProfilePictureView。 - javijuol

3

有一种简单的方法可以获取已登录用户的 Facebook 用户图像。

为了使代码运行,请添加以下导入语句:

import com.facebook.Profile;

看下面的示例(在这个示例中,我使用Picasso库来设置图像):
Uri imageUri = Profile.getCurrentProfile().getProfilePictureUri(400, 400);
Picasso.with(this).load(imageUri).into(imageView);

数字400和400分别表示图片的宽度和高度。


2

可以用另一种方式来写:

ImageView user_picture;
         ImageView userpicture = (ImageView)findViewById(R.id.userpicture);
         URL img_value = null;
         try {
            img_value = new URL("http://graph.facebook.com/"+"100004545962286"+"/picture?type=large");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         Bitmap mIcon1 = null;
        try {
            mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         userpicture.setImageBitmap(mIcon1);

似乎该URL存在重定向,导致图像将为空。 - profimedica

2

使用以下代码使用 Facebook Graph API 获取用户个人资料图片。

     ImageView profileImage = (ImageView) findViewById(R.id.profileImage);
     Bundle params = new Bundle();
     params.putBoolean("redirect", false);
     params.putString("type", "large");
          new GraphRequest(
          AccessToken.getCurrentAccessToken(),
          "me/picture",
          params,
          HttpMethod.GET,
          new GraphRequest.Callback() {
          public void onCompleted(GraphResponse response) {
          try {
            String picUrlString = (String) response.getJSONObject().getJSONObject("data").get("url");
            Glide.with(getApplicationContext()).load(picUrlString).placeholder(R.drawable.ic_launcher).into(profileImage);
          } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }
}
).executeAsync();    

更多信息请参考此链接

或者

获取用户头像简单易行

String UserImageUrl="https://graph.facebook.com/" + facebookUser.getFacebookID() + "/picture?type=large"; 
Glide.with(getApplicationContext()).load(UserImageUrl).placeholder(R.drawable.ic_launcher).into(profileImage); 

这种方式获取用户图像比使用httpclient或webclient下载更好吗?哪种方式更好、更快? - CDrosos

0
private String facebookUser;


AccessToken token;
    token = AccessToken.getCurrentAccessToken();

    facebookUser = AccessToken.getCurrentAccessToken().getUserId();
    ProfilePictureView profilePictureView;
    profilePictureView = (ProfilePictureView) findViewById(R.id.facebookUser);

profilePictureView.setProfileId(facebookUser);

xml
<com.facebook.login.widget.ProfilePictureView
 android:id="@+id/facebookUser"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"></com.facebook.login.widget.ProfilePictureView>

希望能有所帮助!


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