Skip to content

Instantly share code, notes, and snippets.

@quiffman
Created June 16, 2015 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quiffman/1df6608e57493f78f195 to your computer and use it in GitHub Desktop.
Save quiffman/1df6608e57493f78f195 to your computer and use it in GitHub Desktop.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nz.org.geonet.twitterstatuspush;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
/**
*
* @author richardg
*/
public class AcquireAccessToken {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Twitter twitter = new Twitter();
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 aviailable) or just hit enter.[PIN]:");
String pin = br.readLine();
try {
if (pin.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
} else {
accessToken = requestToken.getAccessToken();
}
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
}
//persist to the accessToken for future reference.
storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
Status status = twitter.updateStatus(args[0]);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.exit(0);
}
private static void storeAccessToken(int useId, AccessToken at) {
//store at.getToken()
//store at.getTokenSecret()
System.out.println("token=\"" + at.getToken() +
"\" tokenSecret=\"" + at.getTokenSecret() + "\"");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment