如何将facebook与java桌面应用程序连接起来

时间:2011-02-03 07:42:46

标签: java facebook

我需要从java桌面应用程序连接和验证用户,我使用facebookjsonclient和facebookRestclient尝试了facebook-java-api,但无法获取会话密钥。 Facebook是否有任何变化,因为我们无法连接,或者是否有其他最好的java api或示例如何连接。我的代码是

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

3 个答案:

答案 0 :(得分:0)

首先,您需要获取access_token然后我建议使用restfb库。为了获得令牌,我建议您阅读:https://developers.facebook.com/docs/authentication/

简单摘要:

  1. HTTP GET:https://www.facebook.com/dialog/oauth?  CLIENT_ID = YOUR_APP_ID&安培; REDIRECT_URI = YOUR_URL&安培;范围=电子邮件,read_stream&安培;  RESPONSE_TYPE =记号
  2. 使用您从上面获得的代码,然后执行:https://graph.facebook.com/oauth/access_token?  CLIENT_ID = YOUR_APP_ID&安培; REDIRECT_URI = YOUR_URL&安培;  client_secret = YOUR_APP_SECRET&安培;代码= THE_CODE_FROM_ABOVE
  3. 完成access_token并使用restfb中的FacebookClient来发出API请求。

答案 1 :(得分:0)

AFAIK,目前无法直接从“桌面应用”连接到Facebook。您可以使用apache http客户端库来模仿浏览器并完成它。但总是不能保证工作。我也一直试图用一些图书馆做这件事,但它们似乎已经坏了。

答案 2 :(得分:0)

我这样做了一些成功。我的方法是使用嵌入式浏览器向用户显示身份验证。 Facebook处理身份验证并将您重定向到“登录成功”页面,其中访问令牌和到期时间作为GET数据添加到URL上。下面的大部分代码都是使用org.eclipse.sw t库创建和显示浏览器。

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

因此,您所要做的就是弄清楚您的应用程序需要具有哪些权限才能运行。请注意,用户可以选择“第二个对话框”权限,因此无法保证您实际拥有这些权限。