Google URL Shortener API Integration in java

When you want to use URL Shortener service free of cost and reliable, then the Google URL shortener is the thing for you. This is required where you want to generate a bulk of short URLs with different users related links.

Free Usage: 1,000,000 requests per day 

API Reference 

Let’s see the implementation

1] First you need to get Google API Key from the developer console.

2] Put your key in the below code and it will get the converted short URL. Basically, it will create a bit link URL.


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;  

public class GoogleURLShortener {  

 public static String getShortUrl(String longUrl) {  

	 try {
		  String url = "<>";
		  System.out.println("about to call");
		  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) {
		  //JsonObjectParser jsonObj = new (result.toString());
		  //Object object = jsonObj.get("id");
		  return result.toString();
	 } catch (Exception e) {
	  return null;

3] There are 2 other methods mentioned in the API Reference which you can try out.

Though there are other Short URL services like or tiny URL etc. available to use, in terms of no. of request and short URL generation limit, Google URL shortener I found to be good for our business need. Also, It is backed by Google.

Let me know if there are better services available for free. 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.