How to use Google URL Shortener service in JSF pages

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

https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY"

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": "http://kahimyang.info"}

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

{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/Akt50",
 "longUrl": "http://kahimyang.info"
}

JSF

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="https://www.googleapis.com/urlshortener/"
               + "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");        
        urlConn.setRequestMethod("POST");
        String data = "{\"longUrl\" : \"" + longUrl + "\"}";
        urlConn.addRequestProperty("Content-Length", "" + data.length());
        urlConn.setDoOutput(true);
        urlConn.setDoInput(true);

        //Send the JSON text
        DataOutputStream requestData = new DataOutputStream(
                urlConn.getOutputStream());
        requestData.writeBytes(data);
        requestData.flush();
        requestData.close();

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

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

    } catch (IOException e) {
        return longUrl;
    }

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

    try {

        com.google.gson.Gson gs = new com.google.gson.Gson();
        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="http://twitter.com/share" 
   class="twitter-share-button"
   data-count="horizontal" data-via="kahimyang" 
   data-url="#{evNewsBlogsBean.urlShortener}">Tweet
</a>

<script type="text/javascript" 
     src="http://platform.twitter.com/widgets.js">
</script>

That's it. Good luck.

If you like the article, please share.
(Site URL pattern has changed as a result social actions counter was reset.)



Comment icon   Comments (Newest first)