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

(P) Codever is an open source bookmarks and snippets manager for developers & co. See our How To guides to help you get started. Public bookmarks repos on Github ⭐🙏
Contents
I have just posted my first tweet from Java
” A Visit to Transylvania” by Euromaxx: Lifestyle Europe (DW) https://t.co/MJFDD4540y
— Podcastpedia.org (@podcastpedia) December 21, 2013
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”
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
:
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 https://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) https://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”:
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:
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”:
The new value will be reflected on the “Details” page:
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:
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.
Source code for this post is available on Github - podcastpedia.org is an open source project.