Posts Tagged Twitter

Changes in Twitter4J 2.2.5

Over a year ago, I wrote an article on how to update Twitter status using Twitter4J:
Update your Twitter status with Java
Note that I was using the version 2.1.7 of Twitter4J at that time.

Following a few comments from users who were getting errors, I decided to get my code working on the latest version of Twitter4J, the version 2.2.5. 🙂

This is the two differences I found:

  1. The package twitter4j.http has been renamed twitter4j.auth;
  2. The constructor of the object twitter4j.auth.OAuthAuthorization has changed and now only take an object of type twitter4j.conf.Configuration.

Considering this, please find below the updated code to get the access token:

import java.io.BufferedReader;
import java.io.InputStreamReader;

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

public class TwitterAccessToken {
	private static final String CONSUMER_KEY = "[your consumer key]";
	private static final String CONSUMER_SECRET = "[you consumer secret]";

	public static void main(String[] args) throws Exception {
 		Twitter twitter = new TwitterFactory().getInstance();
		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 available) or just hit enter.[PIN]:");
			String pin = br.readLine();
 			try {
				if (pin.length() > 0) {
					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
				} else {
					accessToken = twitter.getOAuthAccessToken();
				}
			} catch (TwitterException e) {
				if (401 == e.getStatusCode()) {
					System.err.println("Unable to get the access token.");
				} else {
					e.printStackTrace();
				}
			}
		}

		System.out.println("Access Token: " + accessToken.getToken());
		System.out.println("Access Token Secret: " + accessToken.getTokenSecret());
	}
}

And here is the amended code which allows to update your Twitter status:

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterTest {
	private static final String ACCESS_TOKEN = "[your access token]";
	private static final String ACCESS_TOKEN_SECRET = "[your access token secret]";
	private static final String CONSUMER_KEY = "[your consumer key]";
	private static final String CONSUMER_SECRET = "[you consumer secret]";

    public static void main(String[] args) {
    	ConfigurationBuilder builder = new ConfigurationBuilder();
    	builder.setOAuthAccessToken(ACCESS_TOKEN);
    	builder.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    	builder.setOAuthConsumerKey(CONSUMER_KEY);
    	builder.setOAuthConsumerSecret(CONSUMER_SECRET);
        OAuthAuthorization auth = new OAuthAuthorization(builder.build());
        Twitter twitter = new TwitterFactory().getInstance(auth);
		try {
			twitter.updateStatus("Hello World!");
		} catch (TwitterException e) {
			System.err.println("Error occurred while updating the status!");
			return;
		}
        System.out.println("Successfully updated the status.");
    }
}

See you maybe next year for an update on using the version 2.3 of Twitter4j. 😉

, , ,

43 Comments

Update your Twitter status with Java

This article has been written for the version 2.1.7 of Twitter4J. If you want to use a newer version, please read the following article: Changes in Twitter4J 2.2.5

Some time ago, Twitter stopped supporting “Basic Authentication” in the Twitter API, in favour of a new, more secure system, OAuth.
Please read this article for more information about OAuth: http://en.wikipedia.org/wiki/OAuth

The basic authentication was straightforward, you only needed to provide the Twitter username and password in order to authenticate and send tweets from an application. That was it!
But things get more complicated with the new authentication. 🙁
You now need FOUR credentials:

  • A consumer key;
  • A consumer secret;
  • An access token;
  • An access token secret.

Please follow the instructions below to get these credentials for your application:

  1. Register the site as an application on http://dev.twitter.com/apps/new
    • If you’re not currently logged in, use the Twitter username and password which you want associated with this site
    • Your Application’s Name will be what shows up after “via” in your twitter stream. Your application name cannot include the word “Twitter.” I suggest using the name of your web site.
    • Your Application Description can be whatever you want
    • Application Type should be set on Browser
    • The Callback URL should be the URL of your web application
    • Default Access type must be set to Read & Write (this is NOT the default)

    Once you have registered your site as an application, you will be provided with a consumer key and a consumer secret.

  2. Get the access token executing the following code:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    import twitter4j.Twitter;
    import twitter4j.TwitterException;
    import twitter4j.TwitterFactory;
    import twitter4j.http.AccessToken;
    import twitter4j.http.RequestToken;
    
    public class TwitterAccessToken {
    	private static final String CONSUMER_KEY = "[your consumer key]";
    	private static final String CONSUMER_SECRET = "[you consumer secret]";
    	
    	public static void main(String[] args) throws Exception {
     		Twitter twitter = new TwitterFactory().getInstance();
    		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 available) or just hit enter.[PIN]:");
    			String pin = br.readLine();
     			try {
    				if (pin.length() > 0) {
    					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
    				} else {
    					accessToken = twitter.getOAuthAccessToken();
    				}
    			} catch (TwitterException e) {
    				if (401 == e.getStatusCode()) {
    					System.err.println("Unable to get the access token.");
    				} else {
    					e.printStackTrace();
    				}
    			}
    		}
    
    		System.out.println("Access Token: " + accessToken.getToken());
    		System.out.println("Access Token Secret: " + accessToken.getTokenSecret());
    	}
    }
    

    Once you have executed this script and followed the instructions, you will be provided with an access token and an access token secret.

Finally, here is the code to update your Twitter status using the new credentials:

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationContext;
import twitter4j.http.AccessToken;
import twitter4j.http.OAuthAuthorization;

public class TwitterTest {
	private static final String ACCESS_TOKEN = "[your access token]";
	private static final String ACCESS_TOKEN_SECRET = "[your access token secret]";
	private static final String CONSUMER_KEY = "[your consumer key]";
	private static final String CONSUMER_SECRET = "[you consumer secret]";
	
    public static void main(String[] args) {
    	AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    	OAuthAuthorization authorization = new OAuthAuthorization(ConfigurationContext.getInstance(), CONSUMER_KEY, CONSUMER_SECRET, accessToken);
    	Twitter twitter = new TwitterFactory().getInstance(authorization);
		try {
			twitter.updateStatus("Hello World!");
		} catch (TwitterException e) {
			System.err.println("Error occurred while updating the status!");
			return;
		}
        System.out.println("Successfully updated the status.");
    }
}

Please note that this code is using the Java library Twitter4J which helps to integrate a Java application with the Twitter service.

, , , , ,

9 Comments