Learn how to create a simple URL shortener using Java. This project demonstrates how to take a long URL and convert it into a short, SEO-friendly version.
Introduction
A URL shortener is a tool that takes a long URL and converts it into a shorter, more manageable version. The shortened URL redirects to the original URL when clicked. This is a popular technique used for social media sharing and to make links more user-friendly. In this tutorial, we will create a simple URL shortener using the Java programming language.
Objective
The goal of this project is to write a simple Java program that will take a long URL and convert it into a short, SEO-friendly URL. The program will store these short URLs in a database or a simple data structure, and allow redirection to the original URL when needed.
Java Code for URL Shortener
import java.util.HashMap; import java.util.Random; public class URLShortener { private static final String BASE_URL = "http://short.ly/"; private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static HashMap<String, String> urlDatabase = new HashMap<>(); private static Random random = new Random(); // Method to generate a random short URL code public static String generateShortCode() { StringBuilder shortCode = new StringBuilder(); for (int i = 0; i < 6; i++) { int index = random.nextInt(CHARACTERS.length()); shortCode.append(CHARACTERS.charAt(index)); } return shortCode.toString(); } // Method to shorten the URL public static String shortenURL(String longURL) { // Check if the URL is already in the database if (urlDatabase.containsValue(longURL)) { for (String key : urlDatabase.keySet()) { if (urlDatabase.get(key).equals(longURL)) { return BASE_URL + key; } } } // Generate a new short code and store the URL String shortCode = generateShortCode(); urlDatabase.put(shortCode, longURL); return BASE_URL + shortCode; } // Method to retrieve the original URL from the short code public static String getOriginalURL(String shortCode) { return urlDatabase.get(shortCode); } public static void main(String[] args) { // Test the URL shortener String longURL = "https://www.example.com"; String shortURL = shortenURL(longURL); System.out.println("Shortened URL: " + shortURL); // Get the original URL from the short code String shortCode = shortURL.replace(BASE_URL, ""); String originalURL = getOriginalURL(shortCode); System.out.println("Original URL: " + originalURL); } }
Explanation of the Program
This Java program provides a simple implementation of a URL shortener with the following components:
- BASE_URL: The base URL used for generating the short links (e.g., “http://short.ly/”).
- CHARACTERS: A string containing characters that can be used to generate the short URL code.
- urlDatabase: A
HashMap
used to store the mapping of short URL codes to their original long URLs. - generateShortCode: A method that generates a random 6-character short code by selecting random characters from the
CHARACTERS
string. - shortenURL: A method that takes a long URL as input, checks if it already exists in the database, and if not, generates a new short code for it.
- getOriginalURL: A method that takes a short code as input and retrieves the original long URL from the database.
- main: The main method that tests the functionality of the URL shortener by shortening a URL and retrieving the original URL from the short code.
How to Run the Program
- Ensure that you have Java installed on your machine. You can download it from Oracle’s official website.
- Save the provided Java code in a file named
URLShortener.java
. - Open a terminal or command prompt and navigate to the directory where the
URLShortener.java
file is saved. - Compile the Java program by running the following command:
javac URLShortener.java
- Run the compiled Java program using the command:
java URLShortener
- You will see the shortened URL and the corresponding original URL printed on the console.
Greetings! Very helpful advice in this particular article!
It’s the little changes that produce the largest changes.
Many thanks for sharing!
I do not even understand how I ended up right here, however I thought
this put up used to be great. I don’t realize who you might be but
certainly you’re going to a famous blogger when you aren’t already.
Cheers!
Everyone loves it when individuals come together and share views.
Great website, stick with it!
What a material of un-ambiguity and preserveness of precious
familiarity on the topic of unexpected feelings.
After looking at a few of the blog posts on your web page, I honestly like your technique of blogging.
I saved as a favorite it to my bookmark webpage list and will be checking back in the
near future. Please check out my web site too and let
me know how you feel.
Hello! I know this is kind of off-topic however
I needed to ask. Does building a well-established website such as yours require a lot of work?
I am completely new to operating a blog however I do write in my diary every day.
I’d like to start a blog so I can easily share my
personal experience and thoughts online. Please let me know if
you have any kind of recommendations or tips for new
aspiring blog owners. Thankyou!
Hi! I know this is kinda off topic but I was wondering which blog platform are you
using for this website? I’m getting tired of WordPress because I’ve had problems
with haxkers and I’m looking at options for another
platform. I would be fantastic if you could point me in the direction of a
good platform.
That is really interesting, You’re a very professional blogger.
I have joined your rss feed and stay up for in search of more
of your great post. Also, I’ve shared your site in my social networks
I think what you said made a great deal of sense. But,
think on this, what if you were to create a awesome headline?
I ain’t saying your content is not good, but what if you added
something that makes people desire more? I mean URL
Shortener in Java – Learn Programming is a little plain. You might peek at Yahoo’s front page and see how they create article titles
to get people interested. You might add a related video or a related pic
or two to grab people excited about what you’ve written. In my
opinion, it could bring your website a little livelier.
Woah! I’m really loving the template/theme of this website.
It’s simple, yet effective. A lot of times it’s
difficult to get that “perfect balance” between usability and
visual appearance. I must say you have dolne a amazing job with this.
In addition, the blog loads extremely fast for me on Opera.
Exceptional Blog!
Way cool! Some extremely valid points! I appreciate you
writing this write-up and the rest of the site is also very good.
Usually I don’t learn post on blogs, however I wish to
say that this write-up very forced me to take a look at and do it!
Your writing style has been surprised me.
Thanks, quite nice article.
Hi! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading your posts.
Can you recommend any other blogs/websites/forums that cover
the same subjects? Thank you so much!
An impressive share! I’ve just forwarded this onto a friend who has been conducting a little homework on this.
And he actually bought me lunch due to the fact
that I stumbled upon it for him… lol. So let me
reword this…. Thank YOU for the meal!! But
yeah, thanks for spending time to talk about this topic here on your web
page.
I don’teven know how I stopped up right here, however I assumed this
submit used to be great. I do not know who you’re but definitely
you’re going to a famous blogger in case you aren’t already.
Cheers!
We are a bunch of volunteers and opening a brand new scheme in our community.
Your site provided us with valuable information to work on. You’ve performed a formidable task and
our whole group can be thankful to you.
For hottest news you have to go to see web and on the web I found this web site as a best web
site for most up-to-date updates.
WOW just what I was looking for. Came here by searching for laboral
It’s remarkable to pay a quick visit this web site and reading the views of all friends concerning this article, while
I am also keen of getting knowledge.
Thanks very interesting blog!
I’m really impressed together with your writing talents and also
with the layout to your weblog. Is this a paid topic or did
you customize it yourself? Either way keep up the excellent high quality writing,
it’s rare to peer a nice weblog like this one nowadays..
Hey! I know this is kinda off topic but I’d figured I’d ask.
Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
My website goes over a lot of the same subjects as yours and I
feel we could greatly benefit from each other. If you happen to be
interested feel free to send me an email. I look forward to hearing from you!
Excellent blog by the way!
I constantly spent my half an hour to read this weblog’s articles
every day along wiyh a mug of coffee.