Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL shortening algorithm

Tags:

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?

like image 339
Bozho Avatar asked Jan 01 '11 13:01

Bozho


People also ask

How does shortening a URL work?

URL shorteners work by creating a redirect to your long URL. Entering a URL into your internet browser sends an HTTP request to the web server to pull up a specific website. The long and the short URLs are both simply different starting points for an internet browser to get the same destination.

How do you shorten a URL programmatically?

One Simple Solution could be Hashing. Use a hash function to convert long string to short string. In hashing, that may be collisions (2 long URLs map to same short URL) and we need a unique short URL for every long URL so that we can access long URL back.

What is a shortened URL example?

For example, the URL "https://example.com/assets/category_B/subcategory_C/Foo/" can be shortened to " https://example.com/Foo", and the URL " https://en.wikipedia.org/wiki/URL_shortening" can be shortened to " https://w.wiki/U". Often the redirect domain name is shorter than the original one.


1 Answers

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.

like image 128
Uwe Keim Avatar answered Sep 22 '22 08:09

Uwe Keim