-
-
Save adrielAd/cca6696c0474ec5198317ef10c31e42c to your computer and use it in GitHub Desktop.
A sample to shorten url using Google URL Shortener API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment