twitter4j - 从Streaming API

时间:2017-07-11 05:07:32

标签: twitter4j

到目前为止,我从twitter4j网站上的代码示例中获取了什么。它打印出包含我所选关键字的所有推文,因为它们是由Twitter的Streaming API实时提供的,但我想获取实时推文?

class TweetReader {

    public static void main(String[] args) {

        ConfigurationBuilder cb = new ConfigurationBuilder();

        cb.setDebugEnabled(true);

        cb.setOAuthConsumerKey("");
        cb.setOAuthConsumerSecret("");
        cb.setOAuthAccessToken("-");
        cb.setOAuthAccessTokenSecret("");

        try {
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter1 = tf.getInstance();


        //query based on keyword
            Query query = new Query("HDFC");
            query.count(20);

            //search for tweet
            QueryResult result = twitter1.search(query);

           //make a arraylist to store all tweet

            List<TweetData> tweetList = new ArrayList<>();
            for (Status statues : result.getTweets()) {
                TweetData data = new TweetData();
                data.setTweetId("" + statues.getId());
                data.setTweetLanguage(statues.getLang());
                data.setTweetcreatedAt("" + statues.getCreatedAt());
                data.setTweetLocation(statues.getUser().getLocation());
                data.setTweetText(statues.getText());
                data.setFavoriteCount(statues.getFavoriteCount());
                data.setRetweetcount(statues.getRetweetCount());
                data.setInReplyToStatusId(statues.getInReplyToStatusId());
                data.setInReplyToUserId(""+statues.getInReplyToUserId());
                data.setUrlEntities(statues.getURLEntities());
                data.setFollowercount(statues.getUser().getFollowersCount());
                data.setFriendcount(statues.getUser().getFriendsCount());
                data.setUserMentionEntities(statues.getUserMentionEntities());
                data.setHashtagEntities(statues.getHashtagEntities());
                data.setEmail(statues.getUser().getEmail());
                data.setSource(statues.getSource());
                data.setCountrycode(statues.getUser().getWithheldInCountries());

                //insert the tweet into Mongo DB
                Mongodata mongoData = new Mongodata("TEST","127.0.0.1",27017);
                mongoData.add("sma", new Gson().toJson(data));

                //get by key name
                mongoData.getByKey("sma", new Gson().toJson(data));


            //  Map jsonObject = (Map) new Gson().toJson(data);

                //mongoData.getByCondition("sma", jsonObject,"");

                tweetList.add(data);

            }

            // write to DB or write to File, etc using tweetList
            System.out.println(new Gson().toJson(tweetList));

        } catch (TwitterException te) {
            te.printStackTrace();
        }       
    }                 
}

1 个答案:

答案 0 :(得分:2)

您正在使用Twitter搜索API,如果您想要实时检索推文,则需要使用流式传输API。 Twitter4j提供了示例,其中一个是exactly what you are looking for,但是您需要更改行

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

     ConfigurationBuilder cb = new ConfigurationBuilder();
      cb.setDebugEnabled(true).setOAuthConsumerKey("")
              .setOAuthConsumerSecret("")
              .setOAuthAccessToken("")
              .setOAuthAccessTokenSecret("");

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

如果您不这样做,则必须配置属性文件。之后,您将获得此代码

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

public final class PrintSampleStream {

    public static void main(String[] args) throws TwitterException {
         ConfigurationBuilder cb = new ConfigurationBuilder();
          cb.setDebugEnabled(true).setOAuthConsumerKey("")
                  .setOAuthConsumerSecret("")
                  .setOAuthAccessToken("")
                  .setOAuthAccessTokenSecret("");
          TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
                  .getInstance();
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }

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

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

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

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
        twitterStream.addListener(listener);
        twitterStream.sample();
    }
}

随后您将开始接收示例公共流。如果您想获得特定的推文,则需要使用一些过滤器。例如,如果您想要特定查询的推文,则需要更改此行

twitterStream.sample();

带有你想要的单词

FilterQuery filtre = new FilterQuery();
String[] keywordsArray = { "obama" };
filtre.track(keywordsArray);
twitterStream.filter(filtre);

如果您想要从特定配置文件中流式传输推文,则需要使用以下过滤器。您需要为此

更改行twitterStream.sample();
          long[] users = new long[]{someid,someotherid,otherid};
          twitterStream.addListener(listener);
          FilterQuery filtre = new FilterQuery();
          filtre.follow(users);
          twitterStream.filter(filtre);

数组的ID是Twitter用于每个用户的ID。如果您不知道某个用户的ID,可以通过Twitter4j获取它:

User user = tw.showUser("barackobama"); //tw is your Twitter variable from twitter4j.Twitter tw=tf.getInstance();
long id = user.getId();

有更多方法可以从流中检索推文,您只需要阅读文档或在此网站上搜索。祝你好运!