How to post to Twittter from Java with Twitter4J in 10 minutes


Octocat **Promotion** - Efficiently manage your coding bookmarks, aka #codingmarks, on www.codingmarks.org and share your hidden gems with the world. They will be published weekly on Github. Please help us build THE programming-resources location - Star


I have just posted my first tweet from Java

and I still can’t believe how easy and fast it was. The actual coding took like 2 minutes, whereby the remaining 8 minutes were needed to setup a Twitter application to be able to post in the first place. Not only that, but it worked from the first try, therefore I had to stop coding and start blogging about it. This was made possible by Twitter4j (thank you very much Yusuke):

“Twitter4J is an unofficial Java library for the Twitter API. With Twitter4J, you can easily integrate your Java application with the Twitter service. Twitter4J is an unofficial library”

Octocat Source code for this post is available on Github - podcastpedia.org is an open source project.

The example

The tweet you see was generated from a JUnit test method, so let’s have a look…

Configuration

The first thing you need to do is add the twitter4j-core-xxx.jar to the project’s classpath. Because I use Maven, I added the following dependency to the pom.xml file:

<dependency>
	 <groupId>org.twitter4j</groupId>
	 <artifactId>twitter4j-core</artifactId>
	 <version>[3.0,)</version>
 </dependency>

There are a number of properties available for configuring Twitter4J:

  • oauth.consumerKey
  • oauth.consumerSecret
  • oauth.accessToken
  • oauth.accessTokenSecret

If you don’t have these yet, please see the second part of the post – Create a Twitter application – to find out how to get them.

You can specify the properties via twitter4j.properties file, ConfigurationBuilder class or System Property. In the PodcastpediaAdmin project I chose to add a twitter4.properties file in the classpath under src/test/resources:

twitter4j-properties

debug=true
oauth.consumerKey=*********************
oauth.consumerSecret=******************************************
oauth.accessToken=**************************************************
oauth.accessTokenSecret=******************************************

The test method

package org.podcastpedia.admin.general;

import org.apache.log4j.Logger;
import org.junit.Test;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

public class TestTwitterPosting {

	private static Logger LOG = Logger.getLogger(TestTwitterPosting.class);

	@Test
	public void testPostingToTwitter() throws TwitterException{
		Twitter twitter = TwitterFactory.getSingleton();
		String message="\"A Visit to Transylvania\" by Euromaxx: Lifestyle Europe (DW) \n http://bit.ly/1cHB7MH";
		Status status = twitter.updateStatus(message);
		LOG.debug("Successfully updated status to " + status.getText());
	}

}

The code is fairly simple. I have just created a Twitter instance from TwitterFactory, and called the method updateStatus with the message I wanted posted on Twitter.

I ran the test method and in the log console I got:

2013-12-21 07:46:16,461 DEBUG [org.podcastpedia.admin.general.TestTwitterPosting:20] - <Successfully updated status to " A Visit to Transylvania" by Euromaxx: Lifestyle Europe (DW)
 http://t.co/MJFDD4540y>

I couldn’t believe my eyes so I went to check Twitter, and there it was, the tweet shown at the start of the post.

The functionality I need for Podcastpedia.org is pretty much reflected in this test method – the goal is to post tweets for new podcasts directly from the insert-podcasts batch process. So, in production the code will be pretty similar to the one above.

(Appendix) Create a Twitter application

Create a new application

Of course you need to have a Twitter account. You have to log in with into the Twitter Developer Site and create a new application. Click on “Create a new application” -> fill in the form, agree to the Terms and Conditions, answer the CAPTCHA -> and in the end click “Create your Twitter application”:

Create new Twitter application

Create new Twitter application

Add writing permission

Once you’ve done that you will be redirected to your application under My applications. In the “Details” tab you have the “OAuth settings” section:

OAuth settings

Home->My applications->Details:OAuth settings

Notice here the value of the Access level attribute, which is set to Read-only. If you want to post on the wall you need to give grant the app writing permission too. So go to “Settings” tab, select “Read and Write” or “Read, Write and Access direct messages” for “Access”. When you are ready click on “Update this Twitter application’s settings”:

Grant write access

Grant write access

The new value will be reflected on the “Details” page:

write-permission-reflect

Generate Access Token and Access Token Secret

On the “Details” page notice also the Consumer key and Consumer secret values. What we still miss are the Access Token and Access Token Secret values. You can generate them by clicking on the “Create my access token” button at the bottom of the “Details” page. Once you do that, the generated values will be reflected on the bottom of the “Details” page:

OAuth-tokens-generated

You have now all the parameters needed to configure Twitter4J and post on Twitter. I hope you could learn something from this as I did.

Don’t forget to check out Podcastpedia.org – you’ll find for sure other interesting podcasts and episodes. We are grateful for your support.

Octocat Source code for this post is available on Github - podcastpedia.org is an open source project.

Resources

Podcastpedia image

Adrian Matei

Creator of Podcastpedia.org and Codingpedia.org, computer science engineer, husband, father, curious and passionate about science, computers, software, education, economics, social equity, philosophy - but these are just outside labels and not that important, deep inside we are all just consciousness, right?

Parallel calls with async-await in javascript - I promise you all performance and simplicity

I was blown away about the simplicity and performance gain of making parallel calls with the new async-await feature in javascript. See the blog post to understand why. Continue reading