How to use Google URL Shortener service in JSF pages

Saturday November 19, 2011 ()

Google URL shortener service is available free for up to 1,000,000 queries per day against shortened URLS of an account. Is it recommended to use an API key when using the service specially when shortening calls to the API are through an application. You may register to the service in this Google site. Visit the Google URL shortener service here to shorten a URL interactively.

We will demonstrate in this blog how to use Google URL shortener in JSF projects for use with Twitter share data-url. This blog assumes that you already have an API key.

Using the service

Below is the service URL"

Use POST method to this URL to shorten a URL. Content-type of the request should be "application/json" and send/post the request data as JSON string.

{"longUrl": ""}

If the request is successful, the response should look like this:

 "kind": "urlshortener#url",
 "id": "",
 "longUrl": ""


The JSF backing bean should have a method like below.

String longUrl; //  value set from other parts of code;
String shortUrl=null; // 

public String getUrlShortener() {

    if (shortUrl != null) {
        return shortUrl;

    final String G=""
               + "v1/url?key=YOUR_API_KEY"

    try {
        URL url =  new URL(G);

        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.addRequestProperty("User-Agent", "Mozilla");
        urlConn.addRequestProperty("Content-Type", "application/json");        
        String data = "{\"longUrl\" : \"" + longUrl + "\"}";
        urlConn.addRequestProperty("Content-Length", "" + data.length());

        //Send the JSON text
        DataOutputStream requestData = new DataOutputStream(

        //Get response
        InputStream input = urlConn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        String line;
        StringBuilder response = new StringBuilder ();
        while ((line = br.readLine()) != null) {

        br.close(); input.close();
        shortUrl = response.toString();

    } catch (IOException e) {
        return longUrl;

    Map<String, String> a = new HashMap();

    try { gs = new;
        a = gs.fromJson(shortUrl, a.getClass());
        shortUrl = a.get("id");

    } catch (Exception e) {

    if (shortUrl == null) {
         return longUrl;

    return shortUrl;


Below is how we used the shortened URL in one the tweet buttons in one of the pages in this site.

<a href="" 
   data-count="horizontal" data-via="kahimyang" 

<script type="text/javascript" 

That's it. Good luck.


Comments (How to use Google URL Shortener service in JSF pages)