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

Here is the main connection class to connect with 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 = "";

This method gives Code for getting access token from 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;
}

This method will generate graph url to fetch access token.

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

This method get access token from code got from redirect 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;
}
Nilesh Patel
  • 127
  • 2
  • 9

0 Answers0