2014-10-10 78 views
2

我使用Spring社交Twitter来检索朋友的用户名。 这是我的代码。如何在Spring社交Twitter上获得20多个朋友?

@Controller 
@RequestMapping("/") 
    public class HelloController { 

    private Twitter twitter; 

    private ConnectionRepository connectionRepository; 

    @Inject 
    public HelloController(Twitter twitter, ConnectionRepository connectionRepository) { 
     this.twitter = twitter; 
     this.connectionRepository = connectionRepository; 
    } 

    @RequestMapping(method=RequestMethod.GET) 
    public String helloTwitter(Model model) { 
     if (connectionRepository.findPrimaryConnection(Twitter.class) == null) { 
      return "redirect:/connect/twitter"; 
     } 

     model.addAttribute(twitter.userOperations().getUserProfile()); 
     CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends(); 
     model.addAttribute("friends", friends); 
     for (TwitterProfile frnd : friends) { 
      System.out.println(frnd.getName()); 
     } 
     return "hello"; 
    } 

} 

但它只检索到20个朋友。我怎么能得到所有的朋友? (说,如果我有1000个朋友)

+0

我有一个模糊的记忆,Twitter的API页面这类数据,因此你必须反复用X'块检索'元素(在这种情况下,显然是20)。对你没有多大帮助,但在Twitter API页面中应该有一些关于它的文档。 – Mena 2014-10-10 12:32:44

+0

我试图为此找到一个文档。仍然找不到任何。 – 2014-10-10 12:36:53

+0

根据[文档](http://docs.spring.io/spring-social-twitter/docs/1.1.0.RELEASE/apidocs/org/springframework/social/twitter/api/FriendOperations.html#getFriends% 28%29),此方法应该使用对Twitter API的多次调用来检索最多5000个用户。 – 2014-10-10 12:39:19

回答

2

你必须通过所有的游标循环和收集结果如下:

// ... 
    CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends(); 
    ArrayList<TwitterProfile> allFriends = friends; 
    while (friends.hasNext()) { 
     friends = twitter.friendOperations().getFriendsInCursor(friends.getNextCursor()); 
     allFriends.addAll(friends); 
    } 
    // process allFriends... 
+0

你应该使用getFriendIdsInCursor不超过速率限制。 – 2017-07-15 10:51:38

相关问题