Monday, August 03, 2009

Twitter, OAuth, Java and Twitter4j

For alert notifications in Jopr, I am using the Twitter4j library, as well as for the twitter plugin.

As Twitter now requires the usage of OAuth to register new applications, I was looking into this as well. Luckily, Twitter4j has support for OAuth.

Unfortunately this did not work for me ;-(

After some digging, I found the solution (code is the one from the samples page):


...

System.out.println("Open the following URL and grant access to your account:");

System.out.println(requestToken.getAuthorizationURL());

System.out.print("Hit enter when it's done.[Enter]:");

String pin = br.readLine();

 

try{

  accessToken = twitter.getOAuthAccessToken(requestToken, pin);

...


So basically Twitter is returning a PIN to me after I have granted access - and this PIN needs to be passed to the call to get the auth token. This also means to use a different method than in the original example.


2 comments:

Unknown said...

This is nice, but I won't want my Android user to do all the tough things like copying the URL, opening in the browser and getting the PIN back and stuff.
and that too when he's on the go.

Any other method by which my app can do the tough stuff via the code and all the user is required to do is to just provide a userid and password??

much like the signpost way!

Heiko said...

Aman,
you are exactly right. I don't know if it is possible to just open a server socket and thus provide a callback url which could make things easier.

In my Android client "Zwitscher" -- see http://bsd.de/zwitscher/ I've implemented this in a way that the user has to visit Twitter, give the credentials there and then copy or remember the pin, then return to Zwitscher and paste the pin in the respective field - see http://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/LoginActivity.java

I am very open to a better solution too.
I think the base issue is that Twitter.com does not really know how to deal with open source clients.