RestFB: Using a facebook app to get the users Access Token

柔情痞子 提交于 2019-11-30 06:55:46

In addition to what Jack said about AccessToken.getAccessToken() returning the string value of accessToken, you can avoid instantiating DefaultFacebookClient twice by extending DefaultFacebookClient like this:

import com.restfb.DefaultFacebookClient;

public class LoggedInFacebookClient extends DefaultFacebookClient {

    public LoggedInFacebookClient(String appId, String appSecret) {
        AccessToken accessToken = this.obtainAppAccessToken(appId, appSecret);
        this.accessToken = accessToken.getAccessToken();
    }

}

First of all don't confuse app token with user token (more info)

To get user token you have to

  1. Provide a way for user to authenticate against Facebook (more info) and receive "code" - an encrypted string unique to each login request.
  2. Get the user token using this code.

You can get user token with pure RestFB the following way:

private FacebookClient.AccessToken getFacebookUserToken(String code, String redirectUrl) throws IOException {
    String appId = "YOUR_APP_ID";
    String secretKey = "YOUR_SECRET_KEY";

    WebRequestor wr = new DefaultWebRequestor();
    WebRequestor.Response accessTokenResponse = wr.executeGet(
            "https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirectUrl
            + "&client_secret=" + secretKey + "&code=" + code);

    return DefaultFacebookClient.AccessToken.fromQueryString(accessTokenResponse.getBody());
}

The call is simple:

FacebookClient.AccessToken token = getFacebookUserToken(code, redirectUrl);
String accessToken = token.getAccessToken();
Date expires = token.getExpires();
user2492472

Try the following code:

AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();

Per restfb.FacebookClient.AccessToken, you should be able to call accessToken.getAccessToken() -- that should return the String you are looking for.

This will work

AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken("XXXX", "XXXX");
String token=accessToken.getAccessToken();
DefaultFacebookClient facebookClient = new DefaultFacebookClient(token);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!