Google App Engine, Twitter4J and OAuth13 Mar 2010
So I’m writing a Twitter app in Java on Google App Engine right now with my friend, Dave Bright. We’re using Google Web Toolkit for our frontend, and App Engine for hosting and database and such. Twitter4J is our Twitter library of choice.
Since we ran into a spot of trouble using OAuth with the Twitter4J library, I decided to give a bit of a brief tutorial on how to get it working on App Engine. There is actually very different than the code in my as I do some more error checking, and need to do some other stuff with my datastore.
Twitter4J OAuth Overview
- Set the consumer key and secret for your twitter object with setOAuthConsumer(key, secret)
- Get a request token with getRequestToken(callback_uri)
- Persist the request token somewhere, we'll need the original later when we need to get the access token.
- Redirect the user to the URL returned by getAuthorizationURL()
- Get the persisted request token, setOAuthConsumer again.
- Call getOAuthAccessToken(request_token, oauth_verifier) to get an access token
- Persist that token with the user data, you'll need this everytime you want to authenticate.
Some incomplete example code
Please note, this is not code I actually have in production anywhere. It’s original code just for the blog.
The second bit of the code gets called when the user is returned to the page. You need to get the oauth_token and the oauth_verifier GET variables and pass them to this function.
That’s all there really is to it. The Twitter4J library isn’t the best documented library, and just looking at the Javadocs and the Desktop-centric code examples isn’t really that helpful. I hope this clears up some confusion on how to get Twitter4J working with OAuth.