When you want to use URL Shortener service free of cost and reliable, then the Google URL shortener is the thing for you. This is required where you want to generate a bulk of short URLs with different users related links.
Free Usage: 1,000,000 requests per day
Let’s see the implementation
1] First you need to get Google API Key from the developer console.
2] Put your key in the below code and it will get the converted short URL. Basically, it will create a bit link URL.
import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; public class GoogleURLShortener { public static String getShortUrl(String longUrl) { try { String url = "https://www.googleapis.com/urlshortener/v1/url?key=<>"; System.out.println("about to call"); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); // add header post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); post.setHeader("Content-Type", "application/json"); StringEntity params = new StringEntity("{\"longUrl\": \""+longUrl+"\"}"); post.setEntity(params); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println(result); //JsonObjectParser jsonObj = new (result.toString()); //Object object = jsonObj.get("id"); return result.toString(); } catch (Exception e) { return null; } } }
3] There are 2 other methods mentioned in the API Reference which you can try out.
Though there are other Short URL services like bit.ly or tiny URL etc. available to use, in terms of no. of request and short URL generation limit, Google URL shortener I found to be good for our business need. Also, It is backed by Google.
Let me know if there are better services available for free. 🙂