Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter4j : Search for public tweets

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

like image 779
Stormshadow Avatar asked Nov 24 '12 21:11

Stormshadow


1 Answers

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);
        }
}
like image 190
Nikola Davidovic Avatar answered Sep 20 '22 05:09

Nikola Davidovic