How to save an access token?


#1

Hey all,
I’m new to working with APIs but I chose Twitter to learn. I’m making a Java program that uses Twitter4J.

Every time that I start my program, I am given a link that takes me to Twitter to authorize the app, and I receive a PIN that I enter into the program then I can start using the API. I don’t fully understand Oauth yet, but I believe I would like to save these access tokens on my machine.

My goal is to be able to skip getting that link, and having to enter a PIN every time. Any ideas?

Thanks for the help!


#2

So I figured it out. When using the Twitter4J API, there is code provided that will print out a URL and you can enter the PIN and it will create the accessToken. It’s in one of the examples. That code is useful for what follows to initially get the accessTokens and secrets.

To save the token, you can write the following Strings to a file:
String saveAccessToken = accessToken.getToken();
String saveAccessTokenSecret = accessToken.getTokenSecret();
//Eg (Save a CSV file): twitterUserName,saveAccessToken,saveAccessTokenSecret

Then you can read them back in and write:
AccessToken oathAccessToken = new AccessToken(saveAccessToken, saveAccessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);

That’s it!


#3

Thanks, this helped!