Skip to content

Bitly oAuth2 login with bit4j

nischal edited this page Apr 27, 2012 · 1 revision

Here's a simple way to start with bit4j's oAuth login for Bitly.

Client client = new Client(clientId, clientSecret);
BitlyFactory bitlyFactory = new BitlyFactory(client);

In case you are using Google Appengine, then instantiate using the below method

BitlyFactory bitlyFactory = new BitlyFactory(client,HttpClientType.URL_FETCH_SERVICE);

Obtain the redirect URL. For redirect URL, please provide the "exact" same callback URL that you have specified while registering your app on bitly. This is very important "EXACT" same URL which means, http://example.com and http://www.example.com are not EXACT!

String redirectURL = bitlyFactory.getRedirectURL("http://www.callback-url-here.com");

Once the redirect URL is obtained, redirect the user to that URL.


After redirecting the user to bitly, the user comes back to your application post authorization on bitly. Retrieve the "code"

String code = servletRequest.getParameter("code");

Now, get the access token that can be then used to obtain users info. Again, callback URL must be EXACTLY same.

OAuthAccessToken accessToken = bitlyFactory.getOAuthAccessToken(code, "http://www.callback-url-here.com");

Once the access token is obtained, create a new instance of "Bitly". "Bitly" is the only class you'll need (at least at the time of this writing)

Bitly bitly = bitlyFactory.getInstance(accessToken);
ShortUrl shortUrl = bitly.shorten("http://www.grabinbox.com");

Note: You can create a single instance of BitlyFactory and use it throughout your application. For each access token belonging to a user, get a new instance of "Bitly" using BitlyFactory#getInstance(AccessToken)

Clone this wiki locally