Twitter4j 3.0.3 example.

Twitter4j is a java library for Twitter API. Its latest release v3.0.3 is compatible with the twitter API, which requires support of OAuth. We notice that the old version twitter API v1.0 has retired. So, if you are still using API v1.0, you will encounter authentication errors.

Here is some starter code to get started with twitter4j 3.0.3:

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.List;
public class GetTweets {
    public static void main(String[] args) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("----");
        cb.setOAuthConsumerSecret("-----");
        cb.setOAuthAccessToken("------");
        cb.setOAuthAccessTokenSecret("------"); 
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        System.out.println("connected");
        List ss = null;
        try {
            ss = twitter.getUserTimeline();
            System.out.println("Get user timeline:" );
            for(Status s : ss) {
                System.out.println(s.getUser().getName() + ":" + s.getText());
            }
        } catch (TwitterException e) {
            System.out.println("Get timeline: " + e + " Status Code: " + e.getStatusCode());
        }
        // search tweets.
        try {
            Query q = new Query("google");
            QueryResult r = twitter.search(q);
            for(Status s : r.getTweets()) {
                System.out.println("@" + s.getUser().getScreenName() + ":" + s.getText());
            }
        } catch (Exception e) {
            System.err.println("Error search tweets:" + e);
        }
    }
}
You should replace the '----' with your own authentication credentials. Compile the code with command:

javac -classpath /path/to/twitter4j-core-3.0.3.jar GetTweets.java
Run with command:
java -cp /path/to/twitter4j-core-3.0.3.jar:. GetTweets

No comments:

Post a Comment