1

Я использую spring-integration-twitter 4.1.6.RELEASE в моем проекте. Используя TwitterTemplate, я пытался получить всех друзей для аутентифицированного пользователя.Друзья и последователи весной Социальные

Так им с помощью этого метода для него,

friendsList = twitterTemplate.friendOperations().getFriends();

Но в данном случае я только получаю 20 друзей в качестве графа по умолчанию. Но у меня есть 33 друга, и я хочу их всех. Как я могу это сделать. Также я являюсь аутентифицированным пользователем, когда я вызываю этот метод. В TwitterTemplate нет способа передать счетчик в качестве параметра. Но API говорит, что он вернет 5000 пользователей.

/** * Retrieves a list of up to 5000 users that the authenticated user follows. * Note that this method make multiple calls to Twitter's REST API (one call to get a list of the friend IDs and one call for every 100 friends). * If all you need is the friend IDs, consider calling getFriendIds() instead. * Or if you need only a subset of the user's friends, call UserOperations.getUsers() passing in the list of friend IDs you need. * @return a list of TwitterProfiles * @throws ApiException if there is an error while communicating with Twitter. * @throws MissingAuthorizationException if TwitterTemplate was not created with OAuth credentials. */ CursoredList<TwitterProfile> getFriends();

TwitterTemplate называет твиттер API для извлечения данных. Поэтому запросите перенаправление на URL-адрес URL-адреса Twitter API https://api.twitter.com/1.1/friends/list.json.

Twitter API description

В это время, результаты упорядочиваются с самыми последними ниже первой - однако, этот порядок подлежит необъявленным изменения и возможных проблем согласованности. Результаты приведены в группах по 20 пользователей, а несколько «страниц» результатов можно перемещать с помощью следующего значения next_cursor в последующих запросах. См. Использование курсоров для навигации по коллекциям для получения дополнительной информации.

Как я могу достичь этого ???

ответ

0

Наконец нашел решение,

1) Во-первых, вы должны пройти аутентификацию все друг списка пользователя IdS с помощью friendOperations.

2) Затем получите всех друзей для конкретного списка идентификаторов, используя userOperations.

Вот пример фрагмента,

List<org.springframework.social.twitter.api.TwitterProfile> friendsList; 
CursoredList<Long> friendIdList; 
long[] userIdArray; 

friendIdList = twitterTemplate.friendOperations().getFriendIds(); 
userIdArray = new long[friendIdList.size()]; 
for(int i=0; i<friendIdList.size(); i++) 
    userIdArray[i] = friendIdList.get(i); 
friendsList = twitterTemplate.userOperations().getUsers(userIdArray); 
1

Это хорошее решение, но оно не будет возвращать больше, чем первые 100 друзей. Метод twitterTemplate.userOperations.getUsers (userIdArray) может использоваться только для возврата 100 пользователей за раз. https://dev.twitter.com/rest/reference/get/users/lookup

Лучшее решение:

List<TwitterProfile> getAllFollowers() { 
    CursoredList<Long> cursoredList; 
    cursoredList = twitter.friendOperations().getFollowerIds(); 
    List<TwitterProfile> followers = getFollowers(cursoredList); 
    return followers; 
} 

List<TwitterProfile> getFollowers(CursoredList<Long> cursoredList) { 
    List<TwitterProfile> followers = new ArrayList<>(); 
    for(int i = 0; i< cursoredList.size(); i+=100){ 
     followers.addAll(getProfiles(cursoredList, i)); 
    } 
    return followers; 
} 

List<TwitterProfile> getProfiles(CursoredList<Long> cursoredList, int start){ 
    int end = Math.min(start+100, cursoredList.size()); 
    long[] ids = cursoredList.subList(start, end).toArray(new long[0]); 
    List<TwitterProfile> profiles = twitter.userOperations().getUsers(ids); 
    return profiles; 
} 

А затем вызвать getAllFollowers(). Аналогичный код можно использовать и для всех друзей. Просто измените вызов:

twitter.friendOperations.getFollowerIds() 

к

twitter.friendOperations.getFriendIds(); 
0

Чтобы ответить на исходный вопрос, как перемещаться по курсорами, пожалуйста, рассмотрим следующее.

Вы должны перебрать все курсоры и собирать результаты следующим образом:

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