Dec 04 2008
[Tutorial] Accessing the TinyURL “API” from Java
TinyURL is a service that has been around for a while, but recently regained popularity due to its widespread use on Twitter.
Recently, I poked around and wrote up a simple Java method to, given a URL (TinyURL supports only GET requests), generate a TinyURL from it in Java. This is really the only “API” supported by the TinyURL service, but it’s a handy one!
You’ll need Apache HttpClient 3.1 for this.
Without further ado, here’s the code:
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; public abstract class TinyURLUtils { public static String getTinyUrl(String fullUrl) throws HttpException, IOException { HttpClient httpclient = new HttpClient(); // Prepare a request object HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php"); method.setQueryString(new NameValuePair[]{new NameValuePair("url",fullUrl)}); httpclient.executeMethod(method); String tinyUrl = method.getResponseBodyAsString(); method.releaseConnection(); return tinyUrl; } }
Then you’d call the method as follows:
String tinyUrl = TinyURLUtils.getTinyUrl("http://www.mularien.com/blog/"); System.out.println(tinyUrl); // --> http://tinyurl.com/5cporq
You’re welcome to use / improve this code in any way (obviously, I didn’t consider or care about proper exception handling), ideally linking to my blog as the source.
Enjoy!
Note that this makes an HTTP request directly, so this will require some modification if you’re making the call from behind a proxy server. If there’s a need, I can post a follow-up entry on how to set up a proxy server with Apache HTTP Client.


