Post to Twitter using Java

Last modified on August 1st, 2014 by Joe.

In this Twitter+Java tutorial we will see about how to Tweet / post using Java via Twitter API. Twitter provides a rich REST API to create Twitter enabled applications. It provides the complete possibilities, right from reading a timeline to posting the status.

There are two options,


Prerequisite – Twitter Keys

Before going to the code, we should generate Twitter API keys which enables us to access the APIs. These

We need to get “Consumer Key” and “Consumer Secret” from Twitter. Using these two, we should generate, “Access Token” and “Access Token Secret”.

Twitter Consumer Key and Consumer Secret

Go to the URL and create a new application. Give access level in ‘Settings’ as ‘Read, Write and Access direct messages’. You will get both consumer key and secret.

Twitter Consumer Keys

Twitter Access Token

We can generate access tokens using the consumer keys. It can be done using the API or through the interface as well. I am going with generating using the Twitter website itself as shown below. Ensure that the access level comes the same as in consumer keys or regenerate it.

Twitter Access Token

Use Twitter REST API directly in Java

Now we are all set to post to Twitter using Java. In this section, let us see how we can use the REST APIs directly in our Java application. Let us use the status update post Twitter API 

All we need to do is,

  1. set the auth credentials
  2. invoke the URL with required parameters

To make these REST call lets use oauth-signpost and Apache Commons HTTP. Following are the dependent jars to be used,


import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class JavaRestTweet {
	static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

	public static void main(String[] args) throws Exception {
		OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr,
		oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);

		HttpPost httpPost = new HttpPost(


		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = httpClient.execute(httpPost);

		int statusCode = httpResponse.getStatusLine().getStatusCode();
		System.out.println(statusCode + ':'
				+ httpResponse.getStatusLine().getReasonPhrase());


Use Twitter API Wrapper – Twitter4J

Twitter4J is one of the most popular APIs for handling Twitter in Java. If we don’t want to handle the Twitter REST API calls directly as we have shown above and we want go simple then Twitter4J is the way. All we need to do is add only one jar file from Twitter4J twitter4j-core-3.0.5.jar to the dependency and use the respective classes to make the calls.


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class JavaTweet {

	static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

	public static void main(String[] args) {

		try {
			Twitter twitter = new TwitterFactory().getInstance();

			twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
			AccessToken accessToken = new AccessToken(accessTokenStr,


			twitter.updateStatus("Post using Twitter4J Again");

			System.out.println("Successfully updated the status in Twitter.");
		} catch (TwitterException te) {


Post Tweeted to Twitter using Java

Java To Twitter

Comments on "Post to Twitter using Java"

  1. Meet says:

    Hi joe,
    Can we post to twitter only for user for which twitter app is created?
    I mean for each user we have to crete app and access tokens?

  2. Joe says:

    You should provide a OAuth sign in process as part of you application. Then the other user(s) has to authenticate using the provided sign-in process. After this you (your app) can post on behalf of the signed-in user.

  3. Rakesh says:

    what should i enter in
    Callback URL:

  4. Joe says:

    For this example, you can leave it empty. Callback can be used, when we want a page to be called after successful authentication.

  5. Paritosh says:

    Excellent! Joe
    Please write something about posting to facebook using java.

  6. Sumit says:

    HI Paritosh You Can Use RestFB For Facebook ..

  7. John says:

    Hi Joe, can you give an example for oAuth sing in? Thank you!

  8. Anand says:

    Hi, I like this site very much.I regular go through this site. I tried Twitter API Example. Its awesome.
    Please write some post regarding Facebook API. How to connect through Facebook.

  9. Pratik says:

    I will definitely try this

  10. anitha says:

    please write some tutorials for starters who want to learn RESTful web services, build applications using REST

  11. eva says:

    when I try the first method I get the error 403 forbidden. How I can solve it?

  12. Anonymous says:

    Try changing http to https. It should work

  13. Gaurav Singh says:

    i am getting below error, while creating the app, what’s the resolution? –

    Validation failed: Not a valid URL format

  14. Anonymous says:

    Thanks for the tutorial. I am using a different api call (user_timeline.json) but it still works great. I had to change http to https too.

  15. David says:

    Very nice tutorial, you helped me a lot

    Thanks so much. :)

  16. Praveen Kumar says:

    Hi sir. Your tutorials are very easy to understand. very kind of you. Can you help me to send Direct message in Twitter ? I tried possible ways yesterday. Still didn’t find solution. I’m using twitter4j lib.

    MY CODE IS message = twitter.sendDirectMessage(friendUserId, My Messsage);

    I have set Configuration. But still issues are here.

  17. Ram says:

    Hi Sir,

    I am trying to execute,getting below exception please give me the direction to execute.

    Exception in thread “main” Connection refused: connect
    at Method)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(
    at org.apache.http.impl.client.DefaultRequestDirector.execute(
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(
    at org.apache.http.impl.client.CloseableHttpClient.execute(
    at org.apache.http.impl.client.CloseableHttpClient.execute(
    at org.apache.http.impl.client.CloseableHttpClient.execute(
    at JavaRestTweet.main(

  18. Harsha says:

    Hi Joseph,

    I dont have handson on java. Just by running the code whether the post will be displayed on twitter.


Comments are closed for "Post to Twitter using Java".