Changes in Twitter4J 2.2.5


Over a year ago, I wrote an article on how to update Twitter status using Twitter4J:
Update your Twitter status with Java
Note that I was using the version 2.1.7 of Twitter4J at that time.

Following a few comments from users who were getting errors, I decided to get my code working on the latest version of Twitter4J, the version 2.2.5. πŸ™‚

This is the two differences I found:

  1. The package twitter4j.http has been renamed twitter4j.auth;
  2. The constructor of the object twitter4j.auth.OAuthAuthorization has changed and now only take an object of type twitter4j.conf.Configuration.

Considering this, please find below the updated code to get the access token:

import java.io.BufferedReader;
import java.io.InputStreamReader;

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

public class TwitterAccessToken {
	private static final String CONSUMER_KEY = "[your consumer key]";
	private static final String CONSUMER_SECRET = "[you consumer secret]";

	public static void main(String[] args) throws Exception {
 		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		RequestToken requestToken = twitter.getOAuthRequestToken();
		AccessToken accessToken = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (null == accessToken) {
			System.out.println("Open the following URL and grant access to your account:");
			System.out.println(requestToken.getAuthorizationURL());
			System.out.print("Enter the PIN (if available) or just hit enter.[PIN]:");
			String pin = br.readLine();
 			try {
				if (pin.length() > 0) {
					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
				} else {
					accessToken = twitter.getOAuthAccessToken();
				}
			} catch (TwitterException e) {
				if (401 == e.getStatusCode()) {
					System.err.println("Unable to get the access token.");
				} else {
					e.printStackTrace();
				}
			}
		}

		System.out.println("Access Token: " + accessToken.getToken());
		System.out.println("Access Token Secret: " + accessToken.getTokenSecret());
	}
}

And here is the amended code which allows to update your Twitter status:

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterTest {
	private static final String ACCESS_TOKEN = "[your access token]";
	private static final String ACCESS_TOKEN_SECRET = "[your access token secret]";
	private static final String CONSUMER_KEY = "[your consumer key]";
	private static final String CONSUMER_SECRET = "[you consumer secret]";

    public static void main(String[] args) {
    	ConfigurationBuilder builder = new ConfigurationBuilder();
    	builder.setOAuthAccessToken(ACCESS_TOKEN);
    	builder.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    	builder.setOAuthConsumerKey(CONSUMER_KEY);
    	builder.setOAuthConsumerSecret(CONSUMER_SECRET);
        OAuthAuthorization auth = new OAuthAuthorization(builder.build());
        Twitter twitter = new TwitterFactory().getInstance(auth);
		try {
			twitter.updateStatus("Hello World!");
		} catch (TwitterException e) {
			System.err.println("Error occurred while updating the status!");
			return;
		}
        System.out.println("Successfully updated the status.");
    }
}

See you maybe next year for an update on using the version 2.3 of Twitter4j. πŸ˜‰

, , ,


  1. #1 by CuBuff on 09 Apr 2012 - 04:22

    I’m am trying to run this trough netbeans IDE I created my app on twitter (There was not a place to select client or browser?) When I run the code I get the following exception:

    Exception in thread “main” connect timed outRelevant discussions can be on the Internet at:

    witterException{exceptionCode=[bfb606ed-72d7e395 bfb606ed-72d7e36b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}

    What am I doing wrong?

  2. #2 by smoreau on 10 Apr 2012 - 14:31

    I am not sure what you are doing wrong.
    It seems that it cannot connect to the internet. Are you using a proxy?
    If yes, you should configure your app to go through the proxy (cf. http://www.rgagnon.com/javadetails/java-0085.html).
    Otherwise, I would recommend you to read my original article which contains more details: http://www.logikdev.com/2010/12/02/update-your-twitter-status-with-java/

  3. #3 by Albaraa on 30 May 2012 - 22:06

    I get the following errors when I run the twitteraccesstoken any help would be much appreciated thank you!

    Exception in thread “main” java.lang.NoClassDefFoundError: com/google/appengine/api/urlfetch/HTTPRequest
    at twitter4j.internal.http.alternative.HttpClientImpl.request(HttpClientImpl.java:58)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:269)
    at TwitterAccessToken.main(TwitterAccessToken.java:17)
    Caused by: java.lang.ClassNotFoundException: com.google.appengine.api.urlfetch.HTTPRequest
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    … 8 more

  4. #4 by Albaraa on 30 May 2012 - 22:21

    It would really help if you can maybe show your steps as to how you would add twitter4j to library and then how to copy the code into an IDE (I am currently using eclipse)

  5. #5 by Albaraa on 30 May 2012 - 22:29

    Getting these errors now -.-:

    Exception in thread “main” connect timed outRelevant discussions can be on the Internet at:
    http://www.google.co.jp/search?q=bfb606ed or
    http://www.google.co.jp/search?q=72d7e395
    TwitterException{exceptionCode=[bfb606ed-72d7e395 bfb606ed-72d7e36b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:269)
    at TwitterAccessToken.main(TwitterAccessToken.java:17)
    Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
    at sun.net.www.http.HttpClient.(HttpClient.java:233)
    at sun.net.www.http.HttpClient.New(HttpClient.java:306)
    at sun.net.www.http.HttpClient.New(HttpClient.java:323)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
    … 7 more

  6. #6 by smoreau on 30 May 2012 - 22:53

    The first exception is because you didn’t include the Twitter4J library to your classpath.
    The second exception seems to be a network problem. Are you using a proxy?

  7. #7 by Albaraa on 30 May 2012 - 23:09

    Ok I am pretty sure I included the Twitter4j library in classpath right now it is as a reference library the twitter4j-core-2.2.5.jar right?

    I am not using a proxy server.

    I am not that familiar with these things by the way but I have followed the instructions… ='[

  8. #8 by Albaraa on 30 May 2012 - 23:10

    and I added the source file twitter4j-core-2.2.5-sources.jar to it and the Javadoc location: file:/C:/Documents and Settings/alhiyara/Desktop/twitter4j/twitter4j-core/javadoc/

  9. #9 by Albaraa on 30 May 2012 - 23:12

    I could be missing a step or something I am not sure…I haven’t worked on this kind of project before…I wish it wasn’t through OAuth tool >.<

  10. #10 by Albaraa on 30 May 2012 - 23:23

    Btw for the second class the TwitterTest.java I input all 4 credentials and when I run it I get the :

    Error occurred while updating the status!

  11. #11 by smoreau on 31 May 2012 - 12:29

    Hi Albaraa,

    Can you please add the following line after the line 24 of the classe TwitterTest?

    e.printStackTrace();
    

    If you see something like “error – Read-only application cannot POST”, it means that you didn’t allow your application to write on Twitter.
    Please follow the steps on this post to register your application on Twitter : http://www.logikdev.com/2010/12/02/update-your-twitter-status-with-java/

  12. #12 by smoreau on 31 May 2012 - 13:58

    I added the Eclipse project on GitHub for people who want:
    https://github.com/smoreau/TwitterTest

  13. #13 by Albaraa on 31 May 2012 - 16:41

    Ok well here is the deal, the creation of the application is a bit confusing…I thought it was just simply for getting all the keys/codes now I am confused of what is meant exactly by “application” do I actually have to reference a real application? I am just using eclipse now with your classes and added the generated codes…in the application creation for website I just added some random website do I have to actually have a website that runs an app? And I have nothing for the callback URL I have no idea what to put for that…lol sorry I am new to this crap and its confusing the hell out of me and your helping a lot and if you can explain some of these things it would be the best thing ever! THANK YOU!

  14. #14 by Albaraa on 31 May 2012 - 17:37

    All I want to do is to be able to update my twitter status (a little more complicated later on but for now that is all I want to do with this code)…I am not creating this complicated application where I want to update other peoples statuses or whatever…

  15. #15 by smoreau on 31 May 2012 - 20:51

    Hi Albaraa,

    Don’t worry about the term “application”. For Twitter, it is simply an entity which is allowed to communicate with your Twitter account.
    You don’t need to have a website that runs an app. Just put any name you want. Put an existing callback URL, such as your personal website or your Facebook profile. Twitter just needs to have a valid URL, that’s it.

    Yes, this code will allow you to update your Twitter status and only yours.

  16. #16 by Albaraa on 31 May 2012 - 21:35

    I added the e.printStackTrace(); after line 24 like you said and now I get the following errors:

    Error occurred while updating the status!
    connect timed outRelevant discussions can be on the Internet at:
    http://www.google.co.jp/search?q=b2b52c28 or
    http://www.google.co.jp/search?q=1b442895
    TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
    at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
    at TwitterTest.main(TwitterTest.java:23)
    Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
    at sun.net.www.http.HttpClient.(HttpClient.java:233)
    at sun.net.www.http.HttpClient.New(HttpClient.java:306)
    at sun.net.www.http.HttpClient.New(HttpClient.java:323)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
    … 5 more

  17. #17 by Albaraa on 31 May 2012 - 21:39

    Did you add the Java Source Attachment, Javadoc Location, Native Library to the twitter4j-core-2.2.5.jar file after you put it in as a library?

  18. #18 by Albaraa on 31 May 2012 - 21:50

    I got your files that you posted at https://github.com/smoreau/TwitterTest and I got the same errors ='[ I have no idea what I am doing wrong…or like you said maybe something with the network I am going to try it on a different network I will get back to you on that…thanks again for all your help so far

  19. #19 by smoreau on 31 May 2012 - 22:07

    No, I didn’t add the source code, javadoc location to the twitter4j jar file.
    You only need the library, that’s all.

    Your error is a timed out, so it looks like the request to Twitter is not going through. Please check your network.

  20. #20 by Albaraa on 31 May 2012 - 22:14

    I GOT IT TO WORK THANK YOU! lol

  21. #21 by Albaraa on 31 May 2012 - 22:15

    i just switched to a different IDE then eclipse lol I don’t know what the hell was up with that crap thanks for everything again lol

  22. #22 by Albaraa on 31 May 2012 - 22:18

    LOL now I am getting the error again even though I did not change anything lol…anyways ill keep working at it

  23. #23 by Albaraa on 31 May 2012 - 22:20

    Nevermind again I think it gave me the error because I wanted to tweet the same thing again

  24. #24 by smoreau on 31 May 2012 - 22:22

    Well done Albaraa.
    Happy I was able to help. πŸ™‚

  25. #25 by india123 on 29 Jun 2012 - 22:07

    Sir, when i update the status, the count on twitter does not change, is there any way i could change the count?? help needed urgently.Thanks

  26. #26 by smoreau on 30 Jun 2012 - 12:48

    This is quite strange.
    Did you try to clear your cache or wait for a few minutes? The count is maybe taking some time to refresh.
    Let me know if you still have the problem and I will try to reproduce it.

  27. #27 by kirk on 22 Feb 2013 - 07:06

    what we have to write in that call back url while creating a new application on twitter…..i do not have any website . so what shud i do in that case ?

  28. #28 by smoreau on 22 Feb 2013 - 08:32

    Hi Kirk,
    I already answered this question. Don’t hesitate to read the comments, they are often very useful. πŸ˜‰
    For the callback URL, Twitter just needs to have a valid URL, you can put your personal website or your Facebook profile for example.
    Hope it helps.

  29. #29 by kirk on 26 Feb 2013 - 06:52

    dint get the code running….
    output is ” error occured while updating the status !”
    i m running code in eclipse juno

  30. #30 by kirk on 26 Feb 2013 - 06:55

    plz respond soon

  31. #31 by kirk on 26 Feb 2013 - 07:04

    Exception in thread “main” 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
    Failed to validate oauth signature and token

    Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=bfb606ed or
    http://www.google.co.jp/search?q=4ef9707c
    TwitterException{exceptionCode=[bfb606ed-4ef9707c], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:122)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:281)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:273)
    at TwitterAccessToken.main(TwitterAccessToken.java:35)

  32. #32 by kirk on 26 Feb 2013 - 08:30

    now all errors are fixed…but still output is cmng
    ” Error occurred while updating the status! ”
    m using eclipse and for callback url i have given my facebook profile link and for website i also given facebook url .
    steps i m doing –
    1. running twitter acces token class . then output is cmng ” please open the following url ” i m opening it and it is redirecting me to my facebook account . after that message is coming ” enter the pin or just hit enter”
    i m pressing the enter key and i m getting the acces token after that i m running the twitter testjava class. then output is coming unable to update the status. i have given the read and write access to application

  33. #33 by kirk on 26 Feb 2013 - 08:57

    now again # 31 errors are occuring.. plz help me

  34. #34 by smoreau on 26 Feb 2013 - 09:15

    This article has been written a year ago using Twitter4J 2.2.5. However, the latest version is Twitter4J 3.0.3. So I guess the version 2.2.5 is not working with the current Twitter API any longer and you need to migrate to the version 3.0.3.
    I will try to find some time myself to do it, but in the mid-time you can use the following page:
    http://twitter4j.org/en/versions.html#migration21x-22x

  35. #35 by kirk on 26 Feb 2013 - 10:09

    i have added library version 3.03 to external jar in my eclipse but i m using above code . so is there any cordination prblm between api and code synchronization

  36. #36 by smoreau on 26 Feb 2013 - 10:14

    There are some changes to make in order to get the above code to work with the version 3.0.3.
    These changes seem to be explained here : http://twitter4j.org/en/versions.html#migration21x-22x

  37. #37 by kirk on 26 Feb 2013 - 10:24

    i m not able to do these changes because i m not getting it exactly what i have to change … i wud be so thankful to you if you please teach me how to get effective these changes
    thanks

  38. #38 by smoreau on 26 Feb 2013 - 17:52

    Sorry Kirk, I don’t have much time right now for this.
    I will do it as soon as possible.

  39. #39 by kirk on 27 Feb 2013 - 08:31

    no problem dude… thanks

  40. #40 by kirk on 28 Feb 2013 - 05:58

    hey, i m done with that . its wrkng now . thanks so much

  41. #41 by smoreau on 28 Feb 2013 - 08:54

    Well done.
    Can you please explain how you solved it? It could be useful for others. πŸ˜‰

  42. #42 by kirk on 07 Mar 2013 - 07:50

    thnks smoreau
    le me write teh step by step procedure for updating the status / tweet
    1. install twitter 4j library from twitter4j.org
    2. create a project in eclipse with any name .
    3. add the twitter4j-core-3.0.3. jar to your project
    4 .process for adding it – write click on the project then go foe export then click on add externals jar and then add this file and then ok.
    5.create a application on twiiter.dev
    6. get consumer key , consumer secret , access token , access token secret.
    7 .while creating the application in the call back url section put any valid url for example put your linked in profile, gmail profile, facebook profile address or servelt path ( optional). any one of them wud work fine
    8.run the twiiteracceess token.java class on eclipse . after hitting the enter copy the access yoken and access token secret and copy them into twittertest java
    at the defined place.
    9 .run tat class
    10 . you are done

    note: make sure you are updating status each time a new one because if you want to updat ethe same status again you will get error of duplicate status .

    enjoy

  43. #43 by vinay on 07 Apr 2016 - 14:51

    how to fetch twitter data into file by stream

(will not be published)