Skip to content

Instantly share code, notes, and snippets.

@hatak
Created February 12, 2014 04:19
Show Gist options
  • Save hatak/8950004 to your computer and use it in GitHub Desktop.
Save hatak/8950004 to your computer and use it in GitHub Desktop.
get Twitter OAuth
package jp.hatak.twitterbot.util;
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 Auth {
private static final String consumerKey = "set consumer key";
private static final String consumerSecret = "set consumer secret";
public static void main(String args[]) throws Exception{
Twitter twitter = TwitterFactory.getSingleton();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
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();
}
}
}
System.out.println("consumerKey = \"" + consumerKey + "\"");
System.out.println("consumerSecret = \"" + consumerSecret + "\"");
System.out.println("accessToken = \"" + accessToken.getToken() + "\"");
System.out.println("accessTokenSecret = \"" + accessToken.getTokenSecret() + "\"");
System.exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment