How to post tweets using Twitter4j Java API

Here we will discuss on how to post tweets using Twitter4j Java API. Twitter4j is an unofficial Java library and using this you can easily integrate Java application with Twitter service.

You can easily use standalone jar for this twitter4j API or using maven or gradle build tool to download the required jar on the classpath automatically.

Using twitter4j library you can do the following things:

  • Post tweets
  • get timelines from user’s home
  • Send/receive direct message
  • Search for tweets
  • Pagination control
  • Have support for OAuth

In this post I am going to show you how to show timelines and post tweets using twitter4j library.


Eclipse 2020-06, Java at least 1.8, twitter4j 4.0.7

Project Setup

I am going to create gradle based project in Eclipse. The name of the project is java-twitter4j-tweets.

The build.gradle script is given below:

plugins {
    id 'java-library'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {
	implementation 'org.twitter4j:twitter4j-core:4.0.7'

Twitter4j Configuration

There are number of ways you can configure twitter4j API for your Java application. But here I am going to use properties file in the claspath.

Create a file called under src/main/resources folder and put the similar condigurations as shown below.

oauth.consumerKey=<consumer key>
oauth.consumerSecret=<consumer secret>
oauth.accessToken=<access token>
oauth.accessTokenSecret=<sccess token secret>

You can get those details from Twitter Developers under the menu Keys and Tokens.

Show Timelines and Post Tweets

Now we will see how to get timelines from the home and how to post tweets or status on twitter.


import java.util.List;

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

public class TweetManagementApi {

	public static void main(String[] args) throws TwitterException {
		Twitter twitter = TwitterFactory.getSingleton();

		// Timelines
		List<Status> statuses = twitter.getHomeTimeline();

		System.out.println("Showing home timeline.");
		for (Status status : statuses) {
			System.out.println(status.getUser().getName() + ":" + status.getText());

		// Post a tweet
		Status status = twitter.updateStatus("Test");
		System.out.println("Successfully updated the status to [" + status.getText() + "].");


By executing the above code I got the below output, you would have different output:

Showing home timeline.

And for posting tweet:

Successfully updated the status to [Test].

On the twitter home page you will see below output:

post tweets using twitter4j Java api

That’s all about how to post tweets using twitter4j API.

Source Code


Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *