Twitter4j : Search for public tweets

僤鯓⒐⒋嵵緔 提交于 2019-12-20 18:07:53

问题


How does one search within public tweets using the Twitter4j library ?

public static void main(String[] args) {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            Query query = new Query("Cocaine");
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    }

This gives me a Authentication credentials are missing. error


回答1:


You need to register your app for Twitter. You can only do that if you have your own private account. After you obtain ConsumerKey, ConsumerSecret, AccessToken and AccessTokenSecret (they will be presented to you afret you register your application), the simplest solution is to change the code to the following example:

public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
          .setOAuthConsumerKey("yourConsumeKey")
          .setOAuthConsumerSecret("yourConsumerSecret")
          .setOAuthAccessToken("yourAccessToken")
          .setOAuthAccessTokenSecret("yourTokenSecret");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
        try {
            Query query = new Query("query");
            QueryResult result;
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }

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



回答2:


you need to register your application to get an OAuth Authentication Consumerkey, consumersecret and also Accesstoken and Accesstokensecret and provide these values to the configuration builder class.



来源:https://stackoverflow.com/questions/13545936/twitter4j-search-for-public-tweets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!