Dec 01

[Tutorial] URL Shortening in Java using

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 API and decided to write up a quick tutorial on generating URLs from Java.


Since Twitter switched from TinyURL to, I decided I’d take a look at it. Personally, I love the stats tracking features of, 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 account in order to be assigned an API key. Your API key will show up under the “API Key” heading in your account page.

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

Calling’s REST API’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("");
				new NameValuePair[]{
						new NameValuePair("longUrl",",
						new NameValuePair("version","2.0.1"),
						new NameValuePair("login","mybitlylogin"),
						new NameValuePair("apiKey","R_abcdefmyguid"),
						new NameValuePair("format","xml"),
						new NameValuePair("history","1")
		String responseXml = method.getResponseBodyAsString();

Obviously, you would substitute “login” with your 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:


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”

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

    […] URL Shortening in Java using […]

  2. 10 Best URL Shortener Tutorials | RefreshTheNet says:

    […] URL Short­en­ing in Java using […]

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=""> <s> <strike> <strong>