Home | Account | Search  
Java :: Use goo.gl URL shorten from Java
Google API news: the company recently announced an API for its URL shortening service "goo.gl". Developers can use the API to integrate shortened goo.gl URLs into their own projects. It's a RESTful JSON API (documentation is here). I couldn't find an example written in Java, so here is my contribution:

private String googUrl = "https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=<YourAPIKey>";

public String shorten(String longUrl)
{
    String shortUrl = "";

    try
    {
        URLConnection conn = new URL(googUrl).openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter wr =
                     new OutputStreamWriter(conn.getOutputStream());
        wr.write("{\"longUrl\":\"" + longUrl + "\"}");
        wr.flush();

        // Get the response
        BufferedReader rd =
                     new BufferedReader(
                     new InputStreamReader(conn.getInputStream()));
        String line;

        while ((line = rd.readLine()) != null)
        {
            if (line.indexOf("id") > -1)
            {
                // I'm sure there's a more elegant way of parsing
                // the JSON response, but this is quick/dirty =)
                shortUrl = line.substring(8, line.length() - 2);
                break;
            }
        }

        wr.close();
        rd.close();
    }
    catch (MalformedURLException ex)
    {
        Logger.getLogger(ShortenUrl.class.getName()).log(
                                         Level.SEVERE, null, ex);
    }
    catch (IOException ex)
    {
       
Logger.getLogger(ShortenUrl.class.getName()).log(
                                         Level.SEVERE, null, ex);
       
    }

    return shortUrl;
}