Created
December 5, 2011 05:35
-
-
Save roundrop/1432442 to your computer and use it in GitHub Desktop.
A sample to shorten url using Google URL Shortener API.
This file contains 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; | |
} | |
} | |
} |
It returns the same input URL "longUrl "
Google shortner api is now deprecated so this will no longer work.
Look at:
https://firebase.google.com/docs/dynamic-links/create-links
It's thrown the IOException error.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work. It returns the same input URL.