3

是否可以通过直接昵称/密码连接以编程方式访问 fb api?如果没有,在保持它是一个真正的客户端应用程序(没有服务器在任何地方运行)的同时如何连接到 api?

4

2 回答 2

1

不; 您需要使用支持的 OAuth登录流程之一 - 尽管那里有与桌面应用程序兼容的流程,这里有一个示例:https ://developers.facebook.com/docs/howtos/login/login-for-desktop/

于 2012-10-31T18:52:17.937 回答
1

这行得通:) 这是一个丑陋的黑客,它取决于http://developers.facebook.com/docs/reference/api/页面的内容,但它确实有效。那么为什么没有标准化的方法呢?

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

public class Main {

    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException,
        URISyntaxException {

    Main m = new Main();
    m.dosth();
}

public void dosth() throws FailingHttpStatusCodeException, MalformedURLException, IOException, URISyntaxException {
    String accessToken = login(Credentials.username, Credentials.password);

    System.out.println(accessToken);

}

/**
 * @param username
 * @param password
 * @return facebook access token
 * @throws IOException
 * @throws MalformedURLException
 * @throws FailingHttpStatusCodeException
 * @throws URISyntaxException
 */
public String login(String username, String password) throws FailingHttpStatusCodeException, MalformedURLException,
        IOException, URISyntaxException {
    WebClient wc = new WebClient();
    wc.setCssEnabled(false);
    wc.setJavaScriptEnabled(false);
    HtmlPage page = wc.getPage("https://www.facebook.com");
    HtmlForm form = (HtmlForm) page.getElementById("login_form");
    form.getInputByName("email").setValueAttribute(username);
    form.getInputByName("pass").setValueAttribute(password);
    HtmlPage home = null;
    for (DomNode node : form.getDescendants()) {
        if (node instanceof HtmlSubmitInput) {
            home = ((HtmlSubmitInput) node).click();
            break;
        }
    }

    // assume log in worked out

    HtmlPage api = wc.getPage("https://developers.facebook.com/docs/reference/api/");
    HtmlAnchor a = api.getAnchorByText("https://graph.facebook.com/me/friends?access_token=...");
    URI href = new URI(a.getHrefAttribute());
    List<NameValuePair> params = URLEncodedUtils.parse(href, "utf-8");
    for (NameValuePair pair : params) {
        if (pair.getName().equals("access_token")) {
            return pair.getValue();
        }
    }
    return null;
}
}

更新好吧,这实际上不像我想的那样工作,因为您只有在授予“开发者”应用程序权限后才能获得此令牌。

于 2012-11-03T23:15:48.530 回答