我正在开发一个使用Facebook Graph Api来收集有关公共帖子的信息的项目。当更改发布到此帖子时,需要实时更新此数据。我已经看到使用回调网址https://developers.facebook.com/docs/graph-api/reference/app/subscriptions/和https://developers.facebook.com/docs/graph-api/real-time-updates/的实时更新机制..但我不知道在java中这样做。请有人帮我使用一个例子。
答案 0 :(得分: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回调网址验证。它可以是一个servlet或任何其他将处理发布到回调url.Facebook的更新将在需要重新发送的get请求中提供挑战代码。
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将通过发布请求将更新发布到您的回拨网址。