java - Twitter Stream API 获得 100 状态并停止执行

标签 java twitter twitter4j

我正在使用 twitter4j twitter Streaming API 来获取特定标签的推文。 我有很多关键字。我想搜索包含该标签的 100 条推文 目前我正在做的是编写代码来获取单个单词的推文

public class StreamAPI {

    public static void main(String[] args) {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);
        cb.setOAuthConsumerKey("xxxx");
        cb.setOAuthConsumerSecret("xxxxx");
        cb.setOAuthAccessToken("xxxx");
        cb.setOAuthAccessTokenSecret("xxxx");
        cb.setUseSSL(true);
        cb.setUserStreamRepliesAllEnabled(true);


        TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();


        twitterStream.setOAuthAccessToken(accestoken);
        StatusListener listener = new StatusListener() {
            int countTweets = 0;

            public void onStatus(Status status) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
                countTweets++;
                System.out.println(countTweets);
            }

            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning stallWarning) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };

        FilterQuery fq = new FilterQuery();
        String keywords[] = {"ipl"};

        fq.track(keywords);

        twitterStream.addListener(listener);
        twitterStream.filter(fq);

    }

}

在计数达到 100 后,我如何停止该进程,并应返回该 100 条推文作为列表。

请帮助我。

最佳答案

看看下面的代码可能对你有帮助

String token= "Key Word";
Query query = new Query(token);
FileWriter outFile = new FileWriter(token.replaceAll("^#","").concat(".txt"), true);
int numberOfTweets = 1500;
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");
 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);
}
PrintWriter out1 = new PrintWriter(outFile);
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 + " located at " + lat +  ", " + lon);} 
 else 
 //  System.out.println(i + " USER: " + user + " wrote: " + msg.replaceAll("\n",""));
   out1.append(i + " USER: " + user + " wrote: " +msg.replaceAll("\n"," ")  );
   out1.print("\n");
} 
System.out.println("file write succefully");

关于java - Twitter Stream API 获得 100 状态并停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479699/

相关文章:

java - 使用java连接mysql

java - twitter4j:401 身份验证凭据丢失或不正确

java - onSaveInstanceState 给我 parcelable 错误...有时

Java Random double in interval [-1000, 1000]

java - activity_main 无法解析或不是字段

java - 无法使用 Gradle 将工件上传到 Nexus Sonatype

使用 SDK 在 Twitter 上分享 android 图像

ios - 如何在 iOS 中通过 Twitter API 获取用户电子邮件地址?

r - R中的词云+语料库错误

java - Twitter4j:java.lang.IllegalStateException:访问 token 已可用