如何使用Twitter4j在特定标签下检索用户及其粉丝的推文?

时间:2015-05-10 14:26:48

标签: java twitter twitter4j

我正在尝试构建一个twitter4j应用程序,实际创建一个小型的推特网络。这是我的示例代码段:

//Monitoring hashtags
Query query = new Query("#anger"); 
query.setCount(100); //get 100 tweets
query.setSince("2010-01-01");
QueryResult result;  
try { 
     result = twitter.search(query);
     for (Status status : result.getTweets()) 
     {
	     if (status.getText() != null)
	     {
             // Getting followers list of a given user
             ArrayList<User> followers = getFollowers(status.getUser().getScreenName());
	          for (User user : followers) 
		  {
                    if (status.getUser().getScreenName().contains(user.getScreenName()))
		    {
                      System.out.println(status.getUser().getScreenName());
		    }
	          }				    		
	      }
      }
    } catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		         }

我认为此代码应在“#anger”标签下打印existence(names)用户的关注者。但是,当我运行此代码时,它违反了api 1.1速率限制,但有一个例外(消息 - 超出速率限制,代码 - 88)。我怎样才能克服这个问题?

这也是我的getFollowers()方法:

// Getting followers list of a given user
public static ArrayList<User> getFollowers (String usname)
{
  Twitter twitter = initTwitter();
  String username = usname;
  ArrayList<User> followers = new ArrayList<User>();
  long nextCursor = -1;
  do  {
    PagableResponseList<User> usersResponse;
    try 
    {
      usersResponse = twitter.getFollowersList(username, nextCursor);
	  nextCursor = usersResponse.getNextCursor();
	  followers.addAll(usersResponse);
    } 
	catch (TwitterException e) 
	{
	  e.printStackTrace();
	}	   
	  } while (nextCursor > 0);

return followers;	
}

1 个答案:

答案 0 :(得分:0)

调用getFollowers()的速率限制为:

Requests / 15-min window (user auth): 15
Requests / 15-min window (app auth): 30

https://dev.twitter.com/rest/reference/get/followers/list

由于您从for (Status status : result.getTweets())调用了多于此的getFollowers(),因此您会收到速率限制错误。

检查速率限制:

    for (Status status : result.getTweets()) 
     {
         if (status.getText() != null)
         {
             // Getting followers list of a given user
             ArrayList<User> followers = getFollowers(status.getUser().getScreenName());
             // Here, Check if you rate limit has been exceeded. 
             // If so, wait till limit is over and then continue
              .....
         }
     }