You can get twitter4j-core from Maven central repository. For the streaming functionality you also need the twitter4j-stream library:
<dependency> <groupid>org.twitter4j</groupid> <artifactid>twitter4j-core</artifactid> <version>[3.0,)</version> <dependency> <dependency> <groupid>org.twitter4j</groupid> <artifactid>twitter4j-stream</artifactid> <version>[3.0,)</version> </dependency>
Access to Twitters Streaming API is done by OAuth and you have to register your application first to get the needed set of credentials. After signing in with your regular Twitter account you can generate the following credentials and write it down in a twitter4j.properties file.
oauth.consumerKey=************ oauth.consumerSecret=************ oauth.accessToken=************ oauth.accessTokenSecret=************
To read the stream you can get a TwitterStream from the TwitterStreamFactory. Then you implement a Listener called StatusListener with a bunch of methods and your almost done. In the end you start streaming by calling the sample() method (that will stream from the Twitter sample stream).
import twitter4j.*; public class TwitterStreamingClient { public static void main(String[] args) { TwitterStream stream = new TwitterStreamFactory().getInstance(); stream.addListener(new StatusListener() { @Override public void onStatus(Status status) { System.out.println(status.getText()); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {} @Override public void onTrackLimitationNotice(int i) {} @Override public void onScrubGeo(long l, long l2) {} @Override public void onStallWarning(StallWarning stallWarning) {} @Override public void onException(Exception e) {} }); stream.sample(); } }
The Status object gives you all information about a Tweet like content, user, geolocation and many others. Check the Twitter4J documentation for more details.
See also