Dec 01

[Tutorial] URL Shortening in Java using bit.ly

Tag: bitly,java,tinyurl,tutorial,twitterpmularien @ 12:19 am

A while ago, I had written up a tutorial on accessing the TinyURL API from Java. I was recently playing with the bit.ly API and decided to write up a quick tutorial on generating bit.ly URLs from Java.

Why bit.ly?

Since Twitter switched from TinyURL to bit.ly, I decided I’d take a look at it. Personally, I love the stats tracking features of bit.ly, and the ability to store history, and parse the results of the API call in XML or JSON (I use XML in this tutorial).

What you Need

First, you’ll need a bit.ly account in order to be assigned an API key. Your API key will show up under the “API Key” heading in your bit.ly account page.

You’ll also need the Apache Commons HTTP (3.x) library and a recent version of Java.

Calling bit.ly’s REST API

bit.ly’s API is slightly more complex than TinyURL’s, but only very slightly so. Here’s an example of calling the API:

		HttpClient httpclient = new HttpClient();
		HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
		method.setQueryString(
				new NameValuePair[]{
						new NameValuePair("longUrl","http://www.amazon.com/),
						new NameValuePair("version","2.0.1"),
						new NameValuePair("login","mybitlylogin"),
						new NameValuePair("apiKey","R_abcdefmyguid"),
						new NameValuePair("format","xml"),
						new NameValuePair("history","1")
						}
				);
		httpclient.executeMethod(method);
		String responseXml = method.getResponseBodyAsString();

Obviously, you would substitute “login” with your bit.ly login name, and “apiKey” with your API key. This will result in the “longUrl” you pass being returned in an XML structure that looks like the following:

<bitly>
	<errorCode>0</errorCode>
	<errorMessage></errorMessage>
	<results>
		<nodeKeyVal>
			<userHash>JTKXY</userHash>
			<shortKeywordUrl></shortKeywordUrl>
			<hash>1L2iWb</hash>
			<nodeKey><![CDATA[http://www.amazon.com/]]></nodeKey>
			<shortUrl>http://bit.ly/JTKXY</shortUrl>
		</nodeKeyVal>
	</results>
	<statusCode>OK</statusCode>
</bitly>

Processing the Returned XML

To do a “dumb” processing of the returned XML, we can simply do something like the following (depending on what XML APIs you have available, you can get much more sophisticated :) ):

		String retVal = null;
		if(responseXml != null) {
			// parse the XML
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader st = new StringReader(responseXml);
			Document d = db.parse(new InputSource(st));
			NodeList nl = d.getElementsByTagName("shortUrl");
			if(nl != null) {
				Node n = nl.item(0);
				retVal = n.getTextContent();
			}
		}
 
		return retVal;

It appears there is also a very early stage project at Google Code called “bitlyj”, which seems to offer a very straightforward API. I’ll try to post a tutorial for this soon, in the meantime, feel free to check it out here: bitlyj at Google Code. As always, feedback is appreciated!

2 Responses to “[Tutorial] URL Shortening in Java using bit.ly”

  1. 10 Best URL Shortener Tutorials | denbagus blog says:

    [...] URL Shortening in Java using bit.ly [...]

  2. 10 Best URL Shortener Tutorials | RefreshTheNet says:

    [...] URL Short­en­ing in Java using bit.ly [...]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>