使用twitter4j获取特定哈希标记的推文

时间:2015-03-31 11:57:05

标签: java twitter

我正在使用twitter4j stream api来获取特定主题标签的推文,但是我只需要10条推文来获取我所需的主题标签和其他主题标签,我最多可获得5000条推文。

为什么我只收到10条推文,其他5000条推文?

1 个答案:

答案 0 :(得分:0)

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey(" ")
  .setOAuthConsumerSecret(" ")
  .setOAuthAccessToken(" ")
  .setOAuthAccessTokenSecret(" ");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("hashtag");
int numberOfTweets = 7;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();

while (tweets.size () < numberOfTweets) {
  if (numberOfTweets - tweets.size() > 100)
    query.setCount(100);
  else 
    query.setCount(numberOfTweets - tweets.size());
  try {
    QueryResult result = twitter.search(query);
    tweets.addAll(result.getTweets());
    System.out.println("Gathered " + tweets.size() + " tweets"+"\n");
    for (Status t: tweets) 
      if(t.getId() < lastID) 
          lastID = t.getId();

  }

  catch (TwitterException te) {
    System.out.println("Couldn't connect: " + te);
  }; 
  query.setMaxId(lastID-1);
}
for (int i = 0; i < tweets.size(); i++) {
  Status t = (Status) tweets.get(i);

 // GeoLocation loc = t.getGeoLocation();

  String user = t.getUser().getScreenName();
  String msg = t.getText();
  //String time = "";
  //if (loc!=null) {
    //Double lat = t.getGeoLocation().getLatitude();
    //Double lon = t.getGeoLocation().getLongitude();*/
   System.out. println(i + " USER: " + user + " wrote: " + msg + "\n");
  } 
  //else 
    //System.out.println(i + " USER: " + user + " wrote: " + msg+"\n");