Friday, May 6, 2011

Google URL Shortener

Introduction


In this short article, we'll be taking a look at using the Google URL shortener API, using the Google APIs Client Library for Java.
The Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, tweet, or email to friends. You can also use the Google URL Shortener API to programmatically interact with the Google URL Shortener service. This way, you can embed the service in your own applications, and use a simple REST API to store, share, and manage goo.gl short URLs from anywhere on the Internet.

A good starting point for the Google URL shortener API is the Google URL shortener API documentation page. It covers authentication, and the various operations supported by the API. These operations include
  • Shorten a long URL
  • Expand a short URL
  • Look up a short URL's analytics
  • Look up a user's history

In this article we'll focus on shortening a long URL.

Setting up the project


We're going to be using Maven2 to handle the dependencies of our project. We add the com.google.api.client:google-api-client dependency to our pom.xml to ensure that our project has all the required dependencies.

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>com.ecs.google.urlshortener</groupid>
 <artifactid>urlshortener</artifactid>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>urlshortener</name>
  <build>
    <plugins>
      <plugin>
        <artifactid>maven-compiler-plugin</artifactid>
        <version>2.3.2</version>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
    </plugins>
    </build>
 <dependencies>
    <dependency>
      <groupid>com.google.api.client</groupid>
      <artifactid>google-api-client</artifactid>
      <version>1.2.1-alpha</version>
      <exclusions>
        <exclusion>
          <artifactid>jsr305</artifactid>
          <groupid>com.google.code.findbugs</groupid>
        </exclusion>
      </exclusions>
      </dependency>
    </dependencies></project>

Setting up the HTTP Transport

Now that we have the dependencies setup, we can start with the actual coding. The first thing we need to do is setup the HttpTransport. The HttpTransport will be setup using the GoogleHeaders, and we'll be specifying the application/json content-type. (as we'll be sending and receiving JSON strings over HTTP). We also configure the JSON parser on the transport to properly parse the request/response.

// setup the anonymous Google HTTP transport.
        HttpTransport transport = GoogleTransport.create();

        // configure the headers on the transport.
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");

        // configure the JSON parser on the transport.
        transport.addParser(new JsonHttpParser());

Execute the API call

Now that we have the transport setup correctly, we can execute our API call. We'll be using the https://www.googleapis.com/urlshortener/v1/url endpoint and issue a POST request.

public static final String GOOGLE_SHORTENER_URL = "https://www.googleapis.com/urlshortener/v1/url";

        // build the HTTP GET request and URL
        HttpRequest request = transport.buildPostRequest();
        request.setUrl(GOOGLE_SHORTENER_URL);
We'll create a JSON GenericData object, containing the longUrl that we want to shorten. We'll put the GenericData on the request.

// Prepare the JSON data structure.
        GenericData data = new GenericData();
        data.put("longUrl", "http://latifymobile.com/");
        JsonHttpContent content = new JsonHttpContent();
        content.data = data;

        // Set the JSON content on the request.
        request.content = content;

Parsing the response

When executing this request, we can parse the HTTP response using a class we created specifically for the Google Url Shortener.

// Execute the request, and parse the response using our Result class.
        HttpResponse response = request.execute();
        UrlShortenerResult result = response.parseAs(UrlShortenerResult.class);

        // Print the result.
        System.out.println(result.shortUrl);
As you can see, this is what we're getting as a response from the Google Shortener API.

{
"kind": "urlshortener#url",
"id": "http://goo.gl/vl02B",
"longUrl": "http://latifymobile.com/"
}
We create a UrlShortenerResult object to parse the JSON string above, and capture the shortUrl (embedded in the id attribute).

/**
  * JSON UrlShortenerResult object, capturing the id as the shortUrl
  */
    public static class UrlShortenerResult extends GenericJson {
        @Key("id")
        public String shortUrl;
    }
And that's basically it. Our longUrl has been shortened by the API.

References


1 comment:

  1. It would be very useful. It's very time consuming if the url is very long. It would be very great if there are ways to shortened the url.

    Mary from collant cycliste homme 

    ReplyDelete