Saturday Aug 23

Key Concepts

Twitter with Java (Tutorial)

PDFPrintE-mail
Thursday, 14 July 2011 14:00
AddThis Social Bookmark Button

Twitter Development using Java

For those of us who don't know what is Twitter. Twitter is a website, owned and operated by Twitter Inc., which offers a social networking and microblogging service, enabling its users to send and read messages called tweets. Tweets are text-based posts of up to 140 characters displayed on the user's profile page.

Twitter exposes a web services API (http://twitter.com/help/api) and this library is intended to make it even easier for java programmers to use.

In this tutorial i will explain how to use this api and configure your twitter account to post a tweet using Java.

In the following example we will use the Java Tutorial Tweeter account to demonstrate the usage of the Java api Twitter4J.  Twitter4J is an unofficial Java library for the Twitter API. 

Grant access right to your account for your Application

To give your application access right to your account you need first to register your application using the Twitter developer web site : 

https://dev.twitter.com/apps

Create an account or login using your previously created account.

Twitter application registration

On the right upper side you should click on Create an Application button.

Twitter create application form

Fill the form using your specific parameters 

NameDescriptionComments
Name The Java Tutorial Updater

Your application name. This is used to attribute the source of a tweet and in user-facing authorization screens.

Description

Java Tutorial application updater

Your application description, which will be shown in user-facing authorization screens.

Website  http://www.java-tutorial.ch/twitter/application

Your application's publicly accessible home page, where users can go to download, make use of, or find out more information about your application. This fully-qualified URL is used in the source attribution for tweets created by your application and will be shown in user-facing authorization screens.
(If you don't have a URL yet, just put a placeholder here but remember to change it later.)

Click on Create your Twitter Application

You have now a page describing your application 

Twitter application configuration screen

You have two parameters we will use to configure our application : Consumer key and Consumer secret.

Define the Twitter application type

We will define now the type of access our application need. We have three options : 

  • Read only 
  • Read and write
  • Read,Write and Access direct messages 

We will give our application all access using Read,Write and Access direct messages. To change it click on the Settings tab 

Twitter application type configuration

Click on Update this Twitter application's settings 

Create access token

We are now ready to generate our access token. To do it we will click on the Details tab then on Create my access token. You should see the newly created  access token :

 Twitter access token

Twitter access token

If the access token section is not displayed click on the Details tab to force the refresh.
Verify carefully the access level displayed. If the access level is not the one requested you have to recreate the application configuration 

We have now all the oAuth configuration parameters required to configure Twitter4j :

  • Consumer Key
  • Consumer Secret
  • Access Token
  • Access Token Secret

Configure Twitter4J 

Twitter4j use the Twitter API. In previous version it was possible to use Basic Authentication but basic authentication has been removed in August 16th 2010. The new authentication protocol is OAuth.

OAuth (Open Authorization) is an open standard for authorization. It allows users to share their private resources (e.g. photos, videos, contact lists, Twitter account) stored on one site with another site without having to hand out their credentials, typically username and password.

OAuth allows users to hand out tokens instead of credentials to their data hosted by a given service provider. Each token grants access to a specific site (e.g. a video editing site) for specific resources (e.g. just videos from a specific album) and for a defined duration (e.g. the next 2 hours) if needed. This allows a user to grant a third party site access to their information stored with another service provider, without sharing their access permissions or the full extent of their data.

To build and create our application we will use Maven. In Maven the resources are located in src/main/resources. Twitter4J requires a property configuration files called twitter4j.properties. We will put the oAuht configuration parameters in this file : 

Content of twitter4j.properties file : 

debug=true
oauth.consumerKey=z6jlpPvxdEQTEDVJaxJ
oauth.consumerSecret=xjUkN27BZpYz7jCHAQnFur4D4UN4e4ShJosf
oauth.accessToken=295565091-P1YMy4CPLSL763eLuREO8QG3FmcGHCK2ba4I0
oauth.accessTokenSecret=0Kx10s9mtN5AXzxboD56rWNq1vU6W2hSv0fG4uTe

Write your Twitter application

The following Twitter application authenticate in the @TheJavaTutorial tweeter account and update the status  

Twitter java application source

package com.ubiteck.sample;

import java.util.logging.Logger;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TwitterApplication {
    private final Logger logger = Logger.getLogger(TwitterApplication.class.getName());

    public static void main(String[] args) {
        new TwitterApplication().publish();
    }
  
    private void publish(){
       String message="Twitter application using Java http://www.java-tutorial.ch/architecture/twitter-with-java-tutorial";
       try {
           Twitter twitter = new TwitterFactory().getInstance();
           try {
               RequestToken requestToken = twitter.getOAuthRequestToken();
               AccessToken accessToken = null;
               while (null == accessToken) {
                   logger.fine("Open the following URL and grant access to your account:");
                   logger.fine(requestToken.getAuthorizationURL());
                   try {
                           accessToken = twitter.getOAuthAccessToken(requestToken);
                   } catch (TwitterException te) {
                       if (401 == te.getStatusCode()) {
                           logger.severe("Unable to get the access token.");
                       } else {
                           te.printStackTrace();
                       }
                   }
               }
               logger.info("Got access token.");
               logger.info("Access token: " + accessToken.getToken());
               logger.info("Access token secret: " + accessToken.getTokenSecret());
           } catch (IllegalStateException ie) {
               // access token is already available, or consumer key/secret is not set.
               if (!twitter.getAuthorization().isEnabled()) {
                   logger.severe("OAuth consumer key/secret is not set.");
                   return;
               }
           }
           Status status = twitter.updateStatus(message);
           logger.info("Successfully updated the status to [" + status.getText() + "].");
       } catch (TwitterException te) {
           te.printStackTrace();
           logger.severe("Failed to get timeline: " + te.getMessage());
       } 
    }
    

}

The result in my Twitter account displayed the following status : 

Twitter status sample

I hope you enjoyed this article. Feel free to click on Google +1 to recommend this article

. Thanks in advance

Tags: java, access, application, twitter, account, click, token

Java Tutorial on Facebook