gpt4 book ai didi

java - 使用 RestFB 获取所有墙上的帖子和评论

转载 作者:行者123 更新时间:2023-11-30 04:01:12 25 4
gpt4 key购买 nike

首先:我知道有一些类似的主题,我根据它们编写了一些代码(如下所示)。我是 Facebook api 的新手,所以我有点迷失:D
无论如何,我的应用程序必须获取所有墙上的帖子和评论,但我无法获取全部。有人可以帮我吗?以下是我的方法:

public static void getFacebookPosts(String url){            
try{
LoggedFacebookClient client = new LoggedFacebookClient();

Page page = client.fetchObject(url, Page.class);
System.out.println(page.getName());
Connection<Post> pageFeed = client.fetchConnection(page.getId() + "/feed", Post.class);

//Getting posts:
for (List<Post> feed : pageFeed){
for (Post post : feed){
//PRINTING THE POST
getAllPostComments(post.getId(), client);
}
}
}catch(com.restfb.exception.FacebookOAuthException ex){
System.out.println("\n!!!!!!! Token Expired !!!!!!!!\n");
}
}

private static void getAllPostComments(String postId, DefaultFacebookClient client){
int currentCount = 0;
JsonObject jsonObject = client.fetchObject(postId + "/comments", JsonObject.class,
Parameter.with("summary", true), Parameter.with("limit", 1));
long commentsTotalCount = jsonObject.getJsonObject("summary").getLong("total_count");

System.out.println("\nComments:");
boolean pom = true;
while(pom == true){ //There should be "while(currentCount < commentsTotalCount)" but currentCount is always < then commentsTotalCount. That's the problem :)
pom = false;
Connection<Comment> comments = client.fetchConnection(postId + "/comments",
Comment.class, Parameter.with("limit", 50000), Parameter.with("offset", currentCount));

for(Comment komentar : comments.getData()){
pom = true;
currentCount++;
stazenychKomentu++;
String mess = komentar.getMessage().replaceAll("\n", " ").replaceAll("\r", " ");
System.out.println(" [" + currentCount + "]: " + komentar.getFrom().getName() + " ## " + mess);
}
}
celkemKomentu += commentsTotalCount;
System.out.println(currentCount + " / " + commentsTotalCount);
}

这是我获取访问 token 的方式:

public LoggedFacebookClient(){
super();
AccessToken accessToken = this.obtainAppAccessToken(API_KEY, APP_SECRET);
this.accessToken = accessToken.getAccessToken();
}

如果有人能帮助我,我将非常感激。非常感谢,如果我的英语不完美,抱歉。

最佳答案

如果你想获取所有帖子,你只需要这样做:

    while (pageFeed.hasNext()) {
pageFeed = facebookClient.fetchConnectionPage(pageFeed.getNextPageUrl(),Post.class);
}

Parameter.with("limit", xxx) 适用于少于 200 个帖子。并且不要忘记长期访问 token !

GET /oauth/access_token?  
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token}

https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens

关于java - 使用 RestFB 获取所有墙上的帖子和评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com