Use Google URL Shortener

Google URL Shortener

Google offer a service to shorten your long urls for free of cost.
I walk you through the steps to interact with the Google URL Shortener API.

Step 1: Register and create your project using Google Developer Console.

Step 2: Activate the Google URL Shortener API in the Google Developers Console.

Step 3: Get an API key to access this service.

Step 4: Now create a utility class to pass the long url and get shorten version of that url.
Java Code is given below:-

 package com.techiekunal.gus  
 import java.io.BufferedReader;  
 import java.io.InputStreamReader;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.client.HttpClient;  
 import org.apache.http.client.methods.HttpPost;  
 import org.apache.http.entity.StringEntity;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 import com.amazonaws.util.json.JSONObject;  
 public class GoogleURLShortener {  
  private static final Logger logger = LoggerFactory.getLogger(GoogleURLShortener.class);  
  public static String getShortUrl(String longUrl) {  
   logger.info("Get Short URL for " + longUrl);  
  try {  
   String url = "https://www.googleapis.com/urlshortener/v1/url?key=<your API KEY here >";  
   HttpClient client = new DefaultHttpClient();  
   HttpPost post = new HttpPost(url);  
   // add header  
   post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");  
   post.setHeader("Content-Type", "application/json");  
   StringEntity params = new StringEntity("{\"longUrl\": \""+longUrl+"\"}");  
   HttpResponse response = client.execute(post);  
   BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
   StringBuffer result = new StringBuffer();  
   String line = "";  
   while ((line = rd.readLine()) != null) {  
   JSONObject jsonObj = new JSONObject(result.toString());  
   Object object = jsonObj.get("id");  
   return object.toString();  
  } catch (Exception e) {  
   return "";  

Step 5: Say thanks to google for having this service for almost free of cost.

Note :- Google services has daily usage quota which is really a lot even for more than normal usage. More information on this service can be found at https://developers.google.com/url-shortener/v1/getting_started