Search code examples
javaurlurl-shortener

URL shortening algorithm


Now, this is not strictly about URL shortening, but my purpose is such anyway, so let's view it like that. Of course the steps to URL shortening are:

  1. Take the full URL
  2. Generate a unique short string to be the key for the URL
  3. Store the URL and the key in a database (a key-value store would be a perfect match here)

Now, about the second point. Here's what I've come up with:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
UUID uuid = UUID.randomUUID();
dos.writeLong(uuid.getMostSignificantBits());
String encoded = new String(Base64.encodeBase64(baos.toByteArray()), "ISO-8859-1");
String shortUrlKey = StringUtils.left(encoded, 6); // returns the leftmost 6 characters
// check if exists in database, repeat until it does not

Is this good enough?


Solution

  • For a file upload application I wrote, I needed this functionality, too. Having read this SO article, I decided to stick with just some random numbers and check whether they exists in the DB.

    So your aproach is similar to what I did.