URL shortening using google API

apache

URL shortening using Google API

Sometimes we need to share a long URL or we need to tweet them. But because of the length of the URL we are not able to do so. Google provides a service using which we can convert our long URL and squeezes them to fewer character URL. This service of Google is also known as goo.gl

This tutorial will explain us how we can use Google URL shortener and if we gets a short URL, how can we get the main URL out of it using the Google URL Shortener API.

To do so we have to first go through the below mentioned steps to generate API-key from Google console.

  • Register your application using the Google Developers Console.
  • Activate the Google URL Shortener API in the Google Developers Console.
  • Google then provides information you’ll need later, such as a api-key, api secret key, client ID and a client secret.

In this tutorial we are using Google OAuth2.0 API’s

          https://www.googleapis.com/auth/urlshortener

We need below mentioned jar’s in our java project

  • gson-2.1.jar
  • httpclient-4.3.4.jar
  • httpcore-4.3.jar

URL Shortening code sample

Replace google-app-api-key with the actual key from google console


	private static final String GOOGLE_URL_SHORT_API = "https://www.googleapis.com/urlshortener/v1/url";
	private static final String GOOGLE_API_KEY = "<google-app-api-key>";
	
	public static String shortenUrl(String longUrl){
		
		if (longUrl == null) {
		    return longUrl;
		}else if(!longUrl.startsWith("http://") && !longUrl.startsWith("https://")){
			longUrl = "http://"+longUrl;
		}
		try {
		    String json = "{\"longUrl\": \""+longUrl+"\"}";   
		    String apiURL = GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY;
		    
		    HttpPost postRequest = new HttpPost(apiURL);
		    postRequest.setHeader("Content-Type", "application/json");
		    postRequest.setEntity(new StringEntity(json, "UTF-8"));

		    CloseableHttpClient httpClient = HttpClients.createDefault();
		    HttpResponse response = httpClient.execute(postRequest);
		    String responseText = EntityUtils.toString(response.getEntity());           
		    
		    Gson gson = new Gson();
		    @SuppressWarnings("unchecked")
		    HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);

	   	    return res.get("id");   	     
		    
		} catch (MalformedURLException e) {
		    return "error";
		} catch (IOException e) {
		    return "error";
		}
	 }

Actual Long URL from already shortened URL by Google code sample

	private static final String GOOGLE_URL_SHORT_API = "https://www.googleapis.com/urlshortener/v1/url";
	private static final String GOOGLE_API_KEY = "<google-app-api-key>";

	public static String getActualURLAgainstGoogleShortURL(String shortUrl){
		
		if (shortUrl == null) {
		    return shortUrl;
		}else if(!shortUrl.startsWith("http://") && !shortUrl.startsWith("https://")){
			shortUrl = "http://"+shortUrl;
		}
		try {
		    String apiURL =GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY + "&shortUrl=" + shortUrl;
		    HttpGet getRequest = new HttpGet(apiURL);
		    
		    CloseableHttpClient httpClient = HttpClients.createDefault();
		    HttpResponse response = httpClient.execute(getRequest);
		    String responseText = EntityUtils.toString(response.getEntity());           
		    
		    Gson gson = new Gson();
		    @SuppressWarnings("unchecked")
		    HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);

	 	    return res.get("longUrl");  	     
		    
		} catch (MalformedURLException e) {
		    return "error";
		} catch (IOException e) {
		    return "error";
		}
	 }

Final code

	package com.play.ground.google;

	import java.io.IOException;
	import java.net.MalformedURLException;
	import java.util.HashMap;

	import org.apache.http.HttpResponse;
	import org.apache.http.client.methods.HttpGet;
	import org.apache.http.client.methods.HttpPost;
	import org.apache.http.entity.StringEntity;
	import org.apache.http.impl.client.CloseableHttpClient;
	import org.apache.http.impl.client.HttpClients;
	import org.apache.http.util.EntityUtils;

	import com.google.gson.Gson;

	public class GoogleURLShortening {
		private static final String GOOGLE_URL_SHORT_API = "https://www.googleapis.com/urlshortener/v1/url";
		private static final String GOOGLE_API_KEY = "<google-app-api-key>";

		public static void main(String[] args) {
			String longURL = "https://developers.google.com/url-shortener/v1/getting_started#expand";
		
			String googleShortURL = GoogleURLShortening.shortenUrl(longURL);
			String googleBackToLongURL = GoogleURLShortening.getActualURLAgainstGoogleShortURL(googleShortURL);
		
			System.out.println("Short URL by google API :"+googleShortURL);
			System.out.println("Long URL against Short URL by google API :"+googleBackToLongURL);
		}
		public static String shortenUrl(String longUrl){
		
			if (longUrl == null) {
			    return longUrl;
			}else if(!longUrl.startsWith("http://") && !longUrl.startsWith("https://")){
				longUrl = "http://"+longUrl;
			}
			try {
			    String json = "{\"longUrl\": \""+longUrl+"\"}";   
			    String apiURL = GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY;
			    
			    HttpPost postRequest = new HttpPost(apiURL);
			    postRequest.setHeader("Content-Type", "application/json");
			    postRequest.setEntity(new StringEntity(json, "UTF-8"));

			    CloseableHttpClient httpClient = HttpClients.createDefault();
			    HttpResponse response = httpClient.execute(postRequest);
			    String responseText = EntityUtils.toString(response.getEntity());           
			    
			    Gson gson = new Gson();
			    @SuppressWarnings("unchecked")
			    HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);

		   	    return res.get("id");   	     
			    
			} catch (MalformedURLException e) {
			    return "error";
			} catch (IOException e) {
			    return "error";
			}
		 }
	
		public static String getActualURLAgainstGoogleShortURL(String shortUrl){
		
			if (shortUrl == null) {
			    return shortUrl;
			}else if(!shortUrl.startsWith("http://") && !shortUrl.startsWith("https://")){
				shortUrl = "http://"+shortUrl;
			}
			try {
			    String apiURL =GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY + "&shortUrl=" + shortUrl;
			    HttpGet getRequest = new HttpGet(apiURL);
			    
			    CloseableHttpClient httpClient = HttpClients.createDefault();
			    HttpResponse response = httpClient.execute(getRequest);
			    String responseText = EntityUtils.toString(response.getEntity());           
			    
			    Gson gson = new Gson();
			    @SuppressWarnings("unchecked")
			    HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);

		   	    return res.get("longUrl");  	     
			    
			} catch (MalformedURLException e) {
			    return "error";
			} catch (IOException e) {
			    return "error";
			}
		 }
	}