0
How to solve error of getting same user information in login with Facebook for different user in my web application developed in Java?

这是连接 facebook 的主要连接类。

public class FBConnection 
{
public static final String FB_APP_ID = "1729*******";
public static final String FB_APP_SECRET = "2c5******";
public static final String REDIRECT_URI = "http://example.com";
static String accessToken = "";

此方法提供了从 facebook 获取访问令牌的代码。

public String getFBAuthUrl() {
    String fbLoginUrl = "";
try {
         fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="
                + FBConnection.FB_APP_ID + "&redirect_uri="
                + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                + "&scope=email,public_profile";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return fbLoginUrl;
}

此方法将生成图形 url 以获取访问令牌。

public String getFBGraphUrl(String code) {
    String fbGraphUrl = "";
    try {
        fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"
                + "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="
                + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                + "&client_secret=" + FB_APP_SECRET + "&code=" + code;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return fbGraphUrl;
}

此方法从重定向 url 获取的代码中获取访问令牌。

public String getAccessToken(String code) {
    if ("".equals(accessToken)) {
        URL fbGraphURL;
        try {
            fbGraphURL = new URL(getFBGraphUrl(code));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("Invalid code received " + e);
        }
        URLConnection fbConnection;
        StringBuffer b = null;
        try {
            fbConnection = fbGraphURL.openConnection();
            BufferedReader in;
            in = new BufferedReader(new InputStreamReader(fbConnection.getInputStream()));
            String inputLine;
            b = new StringBuffer();
            while ((inputLine = in.readLine()) != null)
                b.append(inputLine + "\n");
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Unable to connect with Facebook " + e);
        }

        accessToken = b.toString();
        if (accessToken.startsWith("{")) {
            throw new RuntimeException("ERROR: Access Token Invalid: " + accessToken);
        }
    }
    return accessToken;
}
4

0 回答 0