Authorize user with twitter 4j



this is my code that asks a user to paste a given url in order to authorize my app by a pin.

This works fine, but the problem is that the same user should authorize my app every time he/she uses it. How can i only ask to authorize my app only for new users but not every time a user uses my app.

Thank you.

Twitter twitter = TwitterFactory.getSingleton();
twitter.setOAuthConsumer( .......);
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(;
while (null == accessToken) {
  System.out.println("Open the following URL and grant access to your account:");
  System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
  String pin = br.readLine();
     if(pin.length() > 0){
       accessToken = twitter.getOAuthAccessToken(requestToken, pin);
       accessToken = twitter.getOAuthAccessToken();
  } catch (TwitterException te) {
    if(401 == te.getStatusCode()){
      System.out.println("Unable to get the access token.");



You’ll need to cache the user’s access token in your code.


Hi i did in another version of my code,

but how could i use these tokens?


You’d need to instantiate the accessToken object using the cached information. There may be some twitter4j samples that the library author can point you to, it is a very mature library that is widely used.


Thank you