1

我正在开发一个项目,该项目使用 Facebook Graph Api 收集有关公共帖子的信息。当此帖子发生更改时,需要实时更新此数据。我已经看到使用回调 url https://developers.facebook.com/docs/graph-api/reference/app/subscriptions/https://developers.facebook.com/docs/graph-api的实时更新机制/real-time-updates/ .. 但我不知道在 java 中这样做。请有人帮我举个例子。

4

1 回答 1

5

实时更新可用于页面和用户对象。它们都需要相应页面或用户的访问令牌。(对于页面,您可以使用我/帐户检查它,或者通过向您的应用授予页面访问权限来获取它)。

第 1 步:您将需要一个公共 ip,facebook 将在其中发布更新。第 2 步:您需要设置您的 fb 应用程序以启动实时更新设置

  String appId = //your app id
  String token = //app token appId|appSecret
  String callbackUrl = //your public url
  PostMethod method = new PostMethod();
  method.setURI(new URI("https://graph.facebook.com/" + appId +
           "/subscriptions?callback_url=" + callbackUrl +
         "&object=page&fields=feed&verify_token=streamInit&method=POST&access_token="+
           token, false));

  HttpClient httpClient = new HttpClient();
  if (method != null) {
        int statusCode = httpClient.executeMethod(method);
        String response = new String(method.getResponseBody());
        if (statusCode == HttpStatus.SC_OK) {

                 //Completed streaming initiation
        }else{
           //Streaming initialization failed"
        }
     }
  } catch (Exception e) {

  }

第 3 步:这将触发 facebook 回调 url 验证。它可以是 servlet 或任何其他将处理发布到回调 url 的更新。Facebook 将在您需要重新发送的获取请求中提供质询代码。

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  Map parametersMap = request.getParameterMap();
  if (parametersMap.size() > 0) {
     if (request.getParameter("hub.mode").equals("streamInit")) {
        System.out.println("Verify Token: " + request.getParameter("hub.verify_token"));
        System.out.println("Challenge number:" + request.getParameter("hub.challenge"));

        String responseToClient = request.getParameter("hub.challenge");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(responseToClient);
        response.getWriter().flush();
        response.getWriter().close();

           //"Completed streaming setup on your url" 
     }
  } 

}

第 3 步:将您的应用程序添加为页面选项卡以订阅该页面的实时更新。您将需要一个页面访问令牌

  String appId = //your application id
  String pageId=//page id to subscribe from
  PostMethod method =
        new PostMethod("https://graph.facebook.com/" + pageId + "/tabs?app_id=" + appId +
              "&method=POST&access_token=" + pageToken);
  HttpClient httpClient = new HttpClient();
  try {
     int statusCode = httpClient.executeMethod(method);
     String response = new String(method.getResponseBody());
     if (statusCode == HttpStatus.SC_OK) {

        // "Completed tab addition"
     }else{
        // "Tab adding failed"
     }

  } catch (Exception e) {
     //"Tab adding failed" 
  }

第 4 步:Facebook 将通过发布请求将更新发布到您的回拨网址。

于 2014-04-25T13:08:37.237 回答