Twitter4j Twitter OAuth Example

Today I’m going to show you some sample code regarding how to send a tweet to twitter using twitter4j and OAuth. The following code example is a command line twitter client that authenticates a user with oAuth and allows them to post a tweet.

All you need to to create a project in your favourite IDE.. for ease of use. Add the twitter4j library to your build path. Compile and run. If you run into any problems shoot them into the comments and I’ll lend a hand. Happy hacking.

package com.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

public class Main {

    public static void main(String args[])
    {
        try
        {
            // The factory instance is re-useable and thread safe.
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer("pESR4xRk4glcGKMCryvdMQ", "ddu3r7IRp0I1luSFOW2iLwKP5pYTY03AZrAjJAVaj8");

            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 = null;
                try
                {
                    pin = br.readLine();
                } catch (IOException ex)
                {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
                try
                {
                    if (pin.length() > 0)
                    {
                        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                    } else
                    {
                        accessToken = twitter.getOAuthAccessToken();
                    }
                } 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(), accessToken);
            Status status = twitter.updateStatus(args[0]);
            System.out.println("Successfully updated the status to [" + status.getText() + "].");
            System.exit(0);
        } catch (TwitterException ex)
        {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void storeAccessToken(User user, AccessToken accessToken)
    {
        System.out.println(user.getScreenName());
    }
}

4 comments

  1. Hi,

    I tried your code, but I don’t know why, I always have the same error: Unable to get the access token.
    I tried others examples but it never works.. Do you know what could be my problem?
    Thank you

    Mathilde

  2. hello.

    i have dowloaded the twitter4j jar sip file and have added it into my buildpath in eclipse as an external jar. however when when trying to import while coding the quick fix shows as if that jar file is not in there and cannot import. what am i doing wrong, your help would be greatly appreciated. thank you.
    matt

  3. This is nice, but I won’t want my Android user to do all the tough things like conpyig the URL, opening in the browser and getting the PIN back and stuff.and that too when he’s on the go.Any other method by which my app can do the tough stuff via the code and all the user is required to do is to just provide a userid and password??much like the signpost way!

Comments are closed.