通过客户端软件使用用户名/密码访问Facebook api

时间:2012-10-31 18:46:38

标签: facebook oauth

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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;
}
}

UPDATE 好吧,这实际上并不像我想象的那样,只有在授予“Developer”应用程序权限后才能获得此令牌。