Create URL shortner or Tiny URL like bitly, goog.gl in Java

Most of us would have used URL shortner or tiny URL websites like bit.ly and goo.gl. These sites help in shortening the long URLs which can be easily shared on twitter and other places where space does matter. So how can we design such URL shortner in Java?

Basically we need a way to reduce a very long URL into some short random code whose length should not be more than say 6 characters. Lets assume we can have characters ranging from ‘a’ to z’, ‘A’ to ‘Z’ and 0 to 9. We can choose from the pool of 62 characters. So total number of 6 character words possible would be 62*62*62*62*62(56800235584). This should be enough to accommodate all possible URLs.

But how to convert a URL string to a number? So for each new URL we need to store it in the database with some unique ID and this ID would be converted into a random string. In the shortenurl method we keep dividing the number(ID) by 62 and add character at ‘mod’ position in ‘code’ character array.

In expandurl method we will convert the random string into an integer which basically would be the ID of the URL present in the database

import java.util.concurrent.ThreadLocalRandom;
 
public class URLShortner {
	private static char[] code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
			.toCharArray();
	static int base = code.length;
 
	public static void main(String[] args) {
		String url = "http://google.com";
		String shorturl = shortenurl(url);
		System.out.println("Short URL is " + shorturl);
		System.out.println("Number is " + expandurl(shorturl));
 
	}
 
	private static long expandurl(String shorturl) {
		long index = 0;
		int iter = 0;
		for (char ch : shorturl.toCharArray()) {
			int pos = new String(code).indexOf(ch);
			index += Math.pow(base, iter++) * pos;
		}
		return index;
	}
 
	private static String shortenurl(String url) {
		// Instead of generating random number you would store the URL in
		// database and get next unique ID
		long number = ThreadLocalRandom.current().nextLong(56800235584l);
		System.out.println("Random number is " + number);
		long div = number;
		int mod = 0;
		String shortURL = "";
		while (div > 0) {
			mod = (int) (div % base);
			div = (int) (div / base);
			shortURL += code[mod];
		}
		return shortURL;
	}
}

One of the output of above code was :

Random number is 39467367069
Short URL is Lgd9eR
Number is 39467367069

So it converts the random number into some random 6 character string and also converts back the 6 character string into the original number

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *