java - 使用 Java 的 Facebook API - NullPointerException 错误
问题描述
我正在使用 Java 的 restfb 库处理 Facebook API。我编写了一个代码来获取用户的时间线帖子,但我不断收到 java.lang.NullPointerException 错误。
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.Page;
import com.restfb.types.Post;
import com.restfb.types.User;
import java.util.List;
public class FacebookAPI {
public static void main(String[] args) {
String accessToken = ""; //No I did not forget that
FacebookClient fbClient = new DefaultFacebookClient(accessToken);
//For some reasons the "DefaultFacebookClient" object is shown strikethrough formated in my IDE, idk what it means.
Page page = fbClient.fetchObject("BillGates", Page.class);
Connection<Post> postFeed = fbClient.fetchConnection(page.getId()+"/feed",Post.class);
for(List<Post> postPage : postFeed){
for(Post aPost : postPage){
System.out.println(aPost.getFrom().getName());
System.out.println("-->"+aPost.getMessage());
System.out.println("fb.com/"+aPost.getId());
}
}
}
}
输出:
facebookapi.FacebookAPI.main(FacebookAPI.java:34) 的线程“主”java.lang.NullPointerException 中的异常
第 34 行是第二个 for 循环。
解决方案
官方facebook文档说:
对于页面上的帖子:
任何有效的访问令牌都可以阅读公共主页上的帖子,但响应不会包含用户信息。
所以 restfb 会返回NULL
。如果您尝试 getName() 到那将导致 NullPointerException。
推荐阅读
- python - Python Dataframe 对象根据条件转换为 JSON
- php - Codeigniter 部署在服务器 htaccess 上
- javascript - 试图检测用户何时达到 100 条消息,然后重置,并将一个添加到 caseCount,但它不起作用,我没有收到任何错误
- python - 为什么在 Windows 上,python3,os.path.abspath 不以相同的方式处理前导斜杠,如果它只是一个 dir 或更多?
- vb.net - 没有使用 searchoption.alldirectories 获取所有子目录
- macos-big-sur - 更新 Big Sur (apple m1) 后卸载的命令行工具
- python - Django - 我想在浏览器中查看这个图
- python - 如何将此列表转换为数据框
- pandas - pandas中日期和整数的比较
- javascript - 有没有办法只允许用户使用移动浏览器进入页面?