facebook-graph-api - 我如何获取access_token然后使用它?

标签 facebook-graph-api facebook facebook-java-api facebook-java-sdk

在我的网络应用程序中,我希望用户使用他们的 Facebook 帐户登录。我是通过重定向 url 来实现的。

 response.sendRedirect("http://www.facebook.com/dialog/oauth/?scope=email,user_about_me&dispplay=popup&client_id={app_id}&redirect_uri=http://example.com/index.jsp&response_type=token");

在index.jsp我在url中获取access_token。但在请求中没有访问 token 。我如何在这里获取访问 token ,然后获取用户电子邮件。 index.jsp 中的 url 如下所示:

  http://example.com/index.jsp#access_token={access_token}

提前致谢。

最佳答案

我实际上刚刚在我的 JSP 项目中得到了这个工作!好的,这是您需要了解的内容。您尝试的方法称为“服务器端”方法(还有一种客户端方法,可以共享许多相同的代码。您将使用两个 URL(我已将其全部包装到一个帮助程序中)我称之为 FacebookConfig,它从 facebook.properties 文件中读取所需内容:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import lombok.Cleanup;
import st.fan.model.users.Listener;

public class FacebookConfig {
  public static String auth_uri;
  public static String id;
  public static String key;

  static{
    Properties properties = new Properties();
    try {
      @Cleanup InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("facebook.properties");
      properties.load(in);
      auth_uri = (String)properties.get("auth_uri");
      id = (String)properties.get("id");
      key = (String)properties.get("key");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static String getOAuthDialogUrl() {
    return "https://www.facebook.com/dialog/oauth?client_id="+id+"&redirect_uri="+auth_uri+"&scope=email";
  }

  public static String getOAuthUrl(String code) {
    return "https://graph.facebook.com/oauth/access_token?client_id="+id+"&redirect_uri="+auth_uri+"&client_secret="+key+"&code="+code;
  }

  public static String getGraphUrl(String token) {
    return "https://graph.facebook.com/me?access_token="+token;
  }

  public static String getProfilePictureUrl(Listener profile) {
    return "https://graph.facebook.com/"+profile.getFacebookId()+"/picture";
  }

  public static String getProfilePictureUrl(Listener profile, String size) {
    return "https://graph.facebook.com/"+profile.getFacebookId()+"/picture?type="+size;
  }
}

现在用户被重定向到 getOAuthDialogUrl(),其中包含名为 http://example.com/auth/facebook/Auth 的 servlet 的 URL其中有这个 doGet() 方法

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  Transaction tx = null;
  Session dao = SessionFactoryUtil.getInstance().getCurrentSession();
  String redirect = "/auth/facebook/sorry";

  try {
    String code = request.getParameter("code");
    if(code != null) {
      String[] pairs = NetUtils.fetch(new URL(FacebookConfig.getOAuthUrl(code))).toString().split("&");
      String accessToken = null;
      Integer expires = null;
      for (String pair : pairs) {
        String[] kv = pair.split("=");
        if (kv.length == 2) {
          if (kv[0].equals("access_token")) {
            accessToken = kv[1];
          }
          if (kv[0].equals("expires")) {
            expires = Integer.valueOf(kv[1]);
          }
        }
      }
      if(accessToken != null && expires != null) {
        try {
          JSONObject fb_profile = new JSONObject(NetUtils.fetch(new URL(FacebookConfig.getGraphUrl(accessToken))));
          tx = dao.beginTransaction();
          ListenerSession session = authenticate(request, dao);
          if(session == null) {
            session = createSession(response, dao);
          }
          String facebookid = fb_profile.getString("id");
          String name = fb_profile.getString("name");
          String email = fb_profile.getString("email");
          String username = facebookid;
          if(fb_profile.has("username")) {
            username = fb_profile.getString("username");
          }
          Listener user = ListenerDAO.findByFacebookId(facebookid, dao);
          if(user != null) {
            user.setDisplayName(name);
            user.setEmail(email);
            dao.save(user);
          } else {
            user = new Listener();
            user.setUsername(username);
            user.setDisplayName(name);
            user.setEmail(email);
            user.setDateCreated(new DateTime());
            user.setFacebookId(facebookid);
            user.setStatus(ListenerStatus.ACTIVE);
            dao.save(user);
          }
          ListenerSessionDAO.link(session, user, dao);
          redirect = "/";
          tx.commit();
        } catch (JSONException e) {
          log.error("Parsing Facebook Graph Response", e);
        }
      } else {
        log.error("Expected values not found!");
        log.error("accessToken="+accessToken);
        log.error("expires="+expires);
      }
    } else {
      log.error("Missing 'code' param!");
    }
  } catch(Exception e) {
    e.printStackTrace(System.out);
  } finally {
    if(dao.isOpen()) {
      dao.close();
    }
  }
  response.sendRedirect(redirect);
}

并且(除了使用 Hibernate、Project Lombok 和一个名为 org.json 的简单 JSON 库之外)我使用一个名为 fetch() 的简单辅助函数,它接受 URL 并将内容作为字符串返回,其中包含以下代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class NetUtils {
  public static String fetch(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    String line;
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while((line = reader.readLine()) != null) {
      builder.append(line);
    }
    return builder.toString();
  }
}

这应该能让你起步:)

关于facebook-graph-api - 我如何获取access_token然后使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7146876/

相关文章:

ios - 如何在 ios 上获取通过 Facebook 登录的用户的名字?

javascript - 获取好友列表

php - 无需登录即可显示公共(public) Facebook 帖子流

c++ - 通过 C/C++ 连接到 Facebook 的最佳方式是什么?

android - 登录到 facebook 一个按钮来打开一个新的 Activity

java - Facebook 图形 API 更改并且现在需要访问 key ,如何编写新的 URL

android - 如何在没有安装 Facebook 应用程序的情况下分享到 Facebook 的链接?

facebook - 如何国际化元标签以供 Facebook 正确解析?

facebook-graph-api - 如何使用 Insights API 异步作业下载 facebook 报告?