Skip to content

Instantly share code, notes, and snippets.

@roundrop
Created December 5, 2011 05:35
Show Gist options
  • Save roundrop/1432442 to your computer and use it in GitHub Desktop.
Save roundrop/1432442 to your computer and use it in GitHub Desktop.
A sample to shorten url using Google URL Shortener API.
package jp.roundrop.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public final class GoogleUrlShortener {
public static String shorten(String longUrl) {
if (longUrl == null) {
return longUrl;
}
try {
URL url = new URL("http://goo.gl/api/url");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "toolbar");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("url=" + URLEncoder.encode(longUrl, "UTF-8"));
writer.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
String json = sb.toString();
return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http")));
} catch (MalformedURLException e) {
return longUrl;
} catch (IOException e) {
return longUrl;
}
}
}
@harshadura
Copy link

This is easy and fine, but it has some daily requests limits.

@gobisankar11
Copy link

not working your program just return same url ... not shorten url

@vinod-bb
Copy link

This doesn't work. It returns the same input URL.

@shashikanth12345
Copy link

It returns the same input URL "longUrl "

@bsutton
Copy link

bsutton commented Jun 6, 2018

Google shortner api is now deprecated so this will no longer work.
Look at:
https://firebase.google.com/docs/dynamic-links/create-links

@vigneshwar-comspade
Copy link

It's thrown the IOException error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment