Java - Twitter API (Twitter4J)

From XennisWiki
Jump to: navigation, search

Twitter4j is an (unofficial) Java library for the Twitter API.

Example

On the official site of Twitter4J many code examples can be found.

First steps

  • Register as Twitter Developer
  • Create an application
    • Justify as appropriate Settings > Application Type
    • Click in Details on the Create my access token button
  • Download Twitter4J
  • Create a new Java project and add all libraries, which you find in the lib folder of Twitter4j, to the Java Build Path

Code - output timeline

The following example outputs your Twitter timeline. The Consumer key, Consumer secret, Access token and Access token secret you find in the Details of your Twitter application.

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;


public class HelloTwitter {


	public static void main(String[] args) {
		printTimeline(getTwitter());
	}

	/**
	 * Get Twitter object.
	 * 
	 * @return Twitter object.
	 */
	public static Twitter getTwitter() {
		Twitter twitter = new TwitterFactory().getInstance();

		// Set access
		twitter.setOAuthConsumer("CONSUMER-KEY", "CONSUMER-SECRET");
		twitter.setOAuthAccessToken(new AccessToken("ACCESS-TOKEN", "ACCESS-TOKEN-SECRET"));

		return twitter;
	}
	
	/**
	 * Print out timeline.
	 * 
	 * @param twitter Twitter object
	 */
	public static void printTimeline(Twitter twitter) {
	    List<Status> statuses;
		try {
			statuses = twitter.getHomeTimeline();
		    System.out.println("Showing home timeline.");
		    for (Status status : statuses) {
		        System.out.println(status.getUser().getName() + ": " +
		                           status.getText());
		    }
		} catch (TwitterException e) {
			e.printStackTrace();
		}		
	}

}

Code - output stream

The following code outputs continuously the Twitter Stream.

import java.io.IOException;

import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;

public class TwitterStream {

	public static void main(String[] args) {
		
		twitter4j.TwitterStream twitterStream = new TwitterStreamFactory()
		.getInstance();

		// Set access
		twitterStream .setOAuthConsumer("CONSUMER-KEY", "CONSUMER-SECRET");
		twitterStream .setOAuthAccessToken(new AccessToken("ACCESS-TOKEN", "ACCESS-TOKEN-SECRET"));
		
		try {
			printStream(twitterStream);
		} catch (TwitterException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Print Twitter stream.
	 * 
	 * @param twitterStream
	 *            Object from TwitterStreamFactory
	 * @throws TwitterException
	 * @throws IOException
	 */
	public static void printStream(twitter4j.TwitterStream twitterStream) throws TwitterException, IOException {
		StatusListener listener = new StatusListener() {

			@Override
			public void onStatus(Status status) {
								System.out.println(status.getUser().getName() + ": " + status.getText());
			}

			@Override
			public void onDeletionNotice(
					StatusDeletionNotice statusDeletionNotice) {
			}

			@Override
			public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
			}

			@Override
			public void onException(Exception ex) {
				ex.printStackTrace();
			}

			@Override
			public void onScrubGeo(long arg0, long arg1) {
			}

			@Override
			public void onStallWarning(StallWarning arg0) {
			}
		};

		twitterStream.addListener(listener);
		// sample() method internally creates a thread which manipulates
		// TwitterStream and calls these adequate listener methods continuously.
		twitterStream.sample();		
	}

}

See also