Url shortening algorithm

Posted by Bozho on Stack Overflow See other posts from Stack Overflow or by Bozho
Published on 2011-01-01T13:54:55Z Indexed on 2011/01/01 14:54 UTC
Read the original article Hit count: 342

Filed under:
|
|

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 2nd 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 shortUrl = StringUtils.left(6); // returns the leftmost 6 characters
// check if exists in database, repeat until it does not

I wonder if this is good enough. Is it?

© Stack Overflow or respective owner

Related posts about java

Related posts about url