Code Examples
Sample codes are located at src/twitter4j/examples/ and you can run each classs using bin/className.cmd|sh.
- Updating status
- Getting Timeline
- Sending / Receiving Direct Messages
- Search for Tweets
- Asynchronous API
- Pagination control
- OAuth support
- Streaming API
You can update "What are you doing?" via Twitter.updateStatus() method.
See also twitter4j.examples.Update.java for detail.
Twitter twitter = new Twitter(twitterID,twitterPassword);
Status status = twitter.updateStatus(latestStatus);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
Twitter.get****Timeline() returns a List of public, friends or specified user's timeline.
See also twitter4j.examples.GetTimelines.java for detail.
Twitter twitter = new Twitter(twitterID,twitterPassword);
List<Status> statuses = twitter.getFriendsTimeline();
System.out.println("Showing friends timeline.");
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}
Doesn't work on Java1.4, or Processing? Check the FAQ!
You can send and receive direct messages via Twitter.sendDirectMessage() / Twitter.getDirectMessages().
See also twitter4j.examples.SendDirectMessage.java for detail.
Twitter twitter = new Twitter(senderID,senderPassword);
sender.sendDirectMessage(recipientId,message);
Twitter receiver = new Twitter(recipientId,recipientPassword);
List<DirectMessage> messages = receiver.getDirectMessages();
for (DirectMessage message : messages) {
System.out.println("Sender:" + message.getSenderScreenName());
System.out.println("Text:" + message.getText() + "\n");
}
Doesn't work on Java1.4, or Processing? Check the FAQ!
You can search for Tweets using Query class and Twitter.search(twitter4j.Query) method as following:
Twitter twitter = new Twitter();
Query query = new Query("source:twitter4j yusukey");
QueryResult result = twitter.search(query);
System.out.println("hits:" + result.getTotal());
for (Tweet tweet : result.getTweets()) {
System.out.println(tweet.getFromUser() + ":" + tweet.getText());
}
Doesn't work on Java1.4, or Processing? Check the FAQ!
It is possible to call the time consuming Twitter APIs asynchronously using twitter4j.AsyncTwitter class along with TwitterListener.
Actual method calls will be done in a separate thread and you can get the responses through TwitterListener interface.
See also twitter4j.examples.AsyncUpdate.java for detail.
AsyncTwitter twitter = new AsyncTwitter(senderId,senderPassword);
twitter.updateStatusAsync(args[2], new TwitterAdapter() {
@Override public void updatedStatus(Status status) {
System.out.println("Successfully updated the status to [" +
status.getText() + "].");
}
@Override public void onException(TwitterException e, int method) {
if (method == AsyncTwitter.UPDATE_STATUS) {
e.printStackTrace();
} else {
throw new AssertionError("Should not happen");
}
}
}
);
Some API supports pagination. Those APIs accept following parameters:
page: page count: number of elements per page since_id: returns elements which id are biggar than the specified id max_id: returns elements which id are smaller than the specified idYou can use Paging class to specify those parameters.
Note that some of above parameters are not accepted by those APIs. Please refer the Support API Matrix to see which parameters are accepted by which methods.
Twitter twitter = new Twitter("user", "password");
// requesting page 2, number of elements per page is 40
Paging paging = new Paging(2, 40);
List statuses = twitter.getFriendsTimeline(paging);
for (Status status : statuses) {
System.out.println(status.getUser().getScreenName() + ":" + status.getText());
}
// requesting page 3, since_id is (long)1000
statuses = twitter.getFriendsTimeline(new Paging(3).sinceId(1000l));
for (Status status : statuses) {
System.out.println(status.getUser().getScreenName() + ":" + status.getText());
}
With OAuth authorization scheme, an application can access the user account without userid/password combination given. You need to register your application at http://twitter.com/oauth_clients/new to acquire consumer key, and consumer secret in advance. key / secret pair can be set via Twitter#setOAuthConsumer(), or following system properties:
-Dtwitter4j.oauth.consumerKey=[consumer key] -Dtwitter4j.oauth.consumerSecret=[consumer secret]Initially, you don't have a permission to access the user's account and need to acquire access token by redirecting the user to an authorization URL as follows:
public static void main(String args[]) thrwos Exception{
Twitter twitter = new Twitter();
twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
String pin = br.readLine();
try{
if(pin.length() > 0){
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}else{
accessToken = requestToken.getAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()){
System.out.println("Unable to get the access token.");
}else{
te.printStackTrace();
}
}
}
//persist to the accessToken for future reference.
storeAccessToken(twitter.verifyCredentials().getId() , at);
Status status = twitter.updateStatus(args[0]);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.exit(0);
}
private void storeAccessToken(int useId, AccessToken at){
//store at.getToken()
//store at.getTokenSecret()
}
After you acquired the AccessToken for the user, the RequestToken is not required anymore. You can persist the AccessToken to any kind of persistent store such as RDBMS, or File system by serializing the object, or by geting the token and the secret from AccessToken#getToken() and AccessToken#getTokenSecret().
public static void main(String args[]) thrwos Exception{
Twitter twitter = new Twitter();
twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
AccessToken accessToken = loadAccessToken(Integer.parseInt(args[0]));
twitter.setAccessToken(accessToken);
Status status = twitter.updateStatus(args[1]);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.exit(0);
}
private AccessToken loadAccessToken(int useId){
String token = // load from a persistent store
String tokenSecret = // load from a persistent store
return new AccessToken(token, tokenSecret);
}
See also:
Twitter API Wiki / OAuth FAQ
There are several methods you can use to get TweetsAPIsYou can search for Tweets using Query class and Twitter.search(twitter4j.Query) method as following:
Twitter twitter = new Twitter();
Query query = new Query("source:twitter4j yusukey");
QueryResult result = twitter.search(query);
System.out.println("hits:" + result.getTotal());
for (Tweet tweet : result.getTweets()) {
System.out.println(tweet.getFromUser() + ":" + tweet.getText());
}
Doesn't work on Java1.4, or Processing? Check the FAQ!