如何在java中使用Twitter API从去年到现在获得推文?

时间:2016-07-22 04:47:39

标签: java api twitter

我编码使用搜索推文从特定位置查找特定推文。但是我想找出从去年到现在发布的推文。我刚收到今天最新推文的结果。我该如何修改我的代码?这是我使用java和 twitter4j-core-3.0.5.jar

的代码
import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class TweetFromParticularLocation {



    public static void main(String[] args) {
//        Twitter twitter= new TwitterFactory().getInstance();
//      
//      twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_SECRET_KEY);
//      twitter.setOAuthAccessToken(new AccessToken(TWITTER_ACCESS_TOKEN,TWITTER_ACCESS_TOKEN_SECRET));

        String CONSUMER_KEY = "key";
          String CONSUMER_KEY_SECRET = "key";

        Twitter twitter= new TwitterFactory().getInstance();

        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);

        String accessToken = "key";
        String accessTokenSecret = "key";
        twitter.setOAuthAccessToken(new AccessToken(accessToken,accessTokenSecret));

        try {
            Query query = new Query("#jumatberkah"); //kalau tweet nya kososng, maka outputnya terminated

            //-6.914744, 107.609810 -- latitude, longitude bandung
            //-6.2115, 106.8452 -- latitude, longitude jakarta
          //-.7893, 113.9213  -- latitude, longitude indonesia

            GeoLocation location = new GeoLocation(-6.2115, 106.8452); //latitude, longitude
            String unit = Query.MILES; // or Query.MILES;  Query.KILOMETERS;
            query.setGeoCode(location, 1, unit); //location, radius, unit

            QueryResult result; 

            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();

                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()+"\n");
                }

            } while ((query = result.nextQuery()) != null);

        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }

    }

}

1 个答案:

答案 0 :(得分:1)

Twitter public Search API仅提供最近一周(7天)的推文样本。如果您需要进一步搜索,则需要使用Twitter上的广告Gnip Historical APIs