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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With