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.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 {
    		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!");
        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.

, , , , ,

  1. #1 by Jhone on 31 Dec 2010 - 18:45

    finally something that really works.
    greate job!!

  2. #2 by Lingadurai on 20 Jun 2011 - 14:13

    this method is undefined for Twitter
    pls give help me…

  3. #3 by smoreau on 20 Jun 2011 - 22:05

    I think you forgot one character in the method name, you need to use twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    Note the character ‘O’ between ‘set’ and ‘AuthConsumer’.

  4. #4 by harsh on 12 Oct 2011 - 17:32

    I am getting this error – Exception in thread “main” java.lang.AssertionError: java.lang.ClassNotFoundException: twitter4j.conf.PropertyConfigurationFactory
    at twitter4j.conf.ConfigurationContext.(ConfigurationContext.java:43)
    at twitter4j.TwitterFactory.(TwitterFactory.java:39)
    at TwitterAccessToken.main(TwitterAccessToken.java:15)
    Caused by: java.lang.ClassNotFoundException: twitter4j.conf.PropertyConfigurationFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at twitter4j.conf.ConfigurationContext.(ConfigurationContext.java:41)

  5. #5 by harsh on 12 Oct 2011 - 17:32

    please help me

  6. #6 by smoreau on 12 Oct 2011 - 19:37

    This post is now nearly one year old. So it is possible that Twitter changed their API which is breaking this code. I will try to have a look at this later.

    However, the exception you are getting is actually a ClassNotFoundException. It seems that your application cannot find the class twitter4j.conf.PropertyConfigurationFactory which is part of the Twitter4J library. Can you check this library is included to your application?

  7. #7 by Pri on 27 Feb 2012 - 06:55

    Unable to compile. the twitter.http.* package is not found in twitter4j jar file.
    Let me know the exact jar file for the same.

  8. #8 by smoreau on 27 Feb 2012 - 08:44

    You can find the twitter4j package on the following page:
    However, please note that I wrote this code more than one year ago so the library might have changed since…

  9. #9 by smoreau on 27 Feb 2012 - 21:49

    Indeed, the twitter.http package cannot be found on the new version of Twitter4J because it has been renamed.
    I rewrote the two above classes to work on the latest version (2.2.5) of Twitter4J and post it here:

(will not be published)