Authorize user with twitter 4j

twitter4j
java

#1

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(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 aviailable) 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 te) {
    if(401 == te.getStatusCode()){
      System.out.println("Unable to get the access token.");
    }else{
      te.printStackTrace();
    }
  }
}

}


#2

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


#3

Hi i did in another version of my code,

but how could i use these tokens?


#4

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.


#5

Thank you


#6