简体   繁体   中英

How to connect facebook with java desktop application

I need to connect and authenticate users from java desk top application , i have tried facebook-java-api using facebookjsonclient and facebookRestclient but not able to get session key. is there any changes in facebook due to which we r not able to connect , or is there asny other best java api or example how to connect. my code is

private static void getUserID(String email, String password){
        String session = null;
        try {

            HttpClient http = new HttpClient();

            http.getHostConfiguration().setHost("www.facebook.com");
            String api_key = "key";
            String secret = "sec";
            FacebookJaxbRestClient client = new FacebookJaxbRestClient(api_key, secret);
                System.out.println("====>"+client.isDesktop());

            String token = client.auth_createToken();
            System.out.println(" :::::::"+token);
            System.out.println(" :::::::::: "+token);
            PostMethod post = new PostMethod("/login.php?");

            post.addParameter("api_key", api_key);


            post.addParameter("email", email);
            post.addParameter("pass", password);


            int postStatus = http.executeMethod(post);
                System.out.println("url : " + post.getURI());
            System.out.println("Response : " + postStatus);
            for (Header h : post.getResponseHeaders()) {
                System.out.println(h);
            }
            session = client.auth_getSession(token); // Here I am getting error
            System.out.println("Session string: " + session);
            long userid = client.users_getLoggedInUser();
            //System.out.println("User Id is : " + userid);*/
        } catch (FacebookException fe) {

            fe.printStackTrace();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

AFAIK , there is no way as of now to connect to facebook from a "desktop app" in a straight forward way. You can use apache http client library to mimick a browser and get it done. But it cannot be guranteed to work always.I have also been trying to do it for sometime with some libraries,but they seem broken.

I've had some success doing this. My approach was to use an embedded browser to display the authentication to the user. Facebook handles the authentication and redirects you to a "login successful" page with the access token and expiration time tacked onto the URL as GET data. Most of the code below is for creating and displaying the browser using the org.eclipse.sw t library.

private static final String APP_ID = "###########";
private static final String PERMISSIONS =
        "COMMA SEPARATED LIST OF REQUESTED PERMISSIONS";
private String access_token;
private long expirationTimeMillis;
/**
 * Implements facebook's authentication flow to obtain an access token. This
 * method displays an embedded browser and defers to facebook to obtain the
 * user's credentials.
 * According to facebook, the request as we make it here should return a
 * token that is valid for 60 days. That means this method should be called
 * once every sixty days.
 */
private void authenticationFlow() {
    Display display = new Display();
    Shell shell = new Shell(display);
    final Browser browser;
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    shell.setLayout(gridLayout);

    try {
        browser = new Browser(shell, SWT.NONE);
    } catch (SWTError e){
        System.err.println("Could not instantiate Browser: " + e.getMessage());
        display.dispose();
        display = null;
        return;
    }
    browser.setJavascriptEnabled(true);

    GridData data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.FILL;
    data.horizontalSpan = 3;
    data.grabExcessHorizontalSpace = true;
    data.grabExcessVerticalSpace = true;
    browser.setLayoutData(data);

    final ProgressBar progressBar = new ProgressBar(shell, SWT.MOZILLA);
    data = new GridData();
    data.horizontalAlignment = GridData.END;
    progressBar.setLayoutData(data);

    /* Event Handling */
    browser.addProgressListener(new ProgressListener(){
        public void changed(ProgressEvent event){
            if(event.total == 0) return;
            int ratio = event.current * 100 / event.total;
            progressBar.setSelection(ratio);
        }
        public void completed(ProgressEvent event) {
            progressBar.setSelection(0);
        }
    });
    browser.addLocationListener(new LocationListener(){
        public void changed(LocationEvent e){
            // Grab the token if the browser has been redirected to
            // the login_success page
            String s = e.location;
            String token_identifier = "access_token=";
            if(s.contains("https://www.facebook.com/connect/login_success.html#access_token=")){
                access_token = s.substring(s.lastIndexOf(token_identifier)+token_identifier.length(),s.lastIndexOf('&'));
                String expires_in = s.substring(s.lastIndexOf('=')+1);
                expirationTimeMillis = System.currentTimeMillis() + (Integer.parseInt(expires_in) * 1000);
            }
        }
        public void changing(LocationEvent e){}
    });

    if(display != null){
        shell.open();
        browser.setUrl("https://www.facebook.com/dialog/oauth?"
                + "client_id=" + APP_ID
                + "&redirect_uri=https://www.facebook.com/connect/login_success.html"
                + "&scope=" + PERMISSIONS
                + "&response_type=token");
        while(!shell.isDisposed()) {
            if(!display.readAndDispatch()){
                display.sleep();
                if(access_token != null && !access_token.isEmpty()){
                    try{ Thread.sleep(3000);}catch(Exception e){}
                    shell.dispose();
                }
            }
        }
        display.dispose();
    }
}

So all you have to do is figure out what permissions you're going to need to have for your application to work. Be aware that "second dialog" permissions can be picked from by the user so there is no guarantee that you will actually have these permissions.

First off, you need to get the access_token and then I would recommend using restfb library. In order to get the token I would recommend reading this: https://developers.facebook.com/docs/authentication/

A simple summary:

  1. HTTP GET: https://www.facebook.com/dialog/oauth ? client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream& response_type=token
  2. Use the code you get from above and then, do: https://graph.facebook.com/oauth/access_token ? client_id=YOUR_APP_ID&redirect_uri=YOUR_URL& client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
  3. Exact the access_token and use FacebookClient from restfb to make the API requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM