Their is a bit.ly API that uses OAuth, but for what I wanted to do, I decided that was overkill, as I didn't necessarily need to associate the shortened URLs to a users bit.ly account, all I really cared about was getting a shortened URL.
Fortunately, Google came to the rescue with their goo.gl URL shortening service that also exposes a public API without need for authentication.
So I simply wrote a service class that utilised the Spring RestTemplate class to shorten URLs:
@Service("urlShortenService") public class UrlShortenService { private RestTemplate restTemplate; public UrlShortenService() { restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory()); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new MappingJacksonHttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); } public String shortenUrl(String url) { Map<String, String> request = new HashMap<String, String>(); request.put("longUrl", url); LinkedHashMap<String, String> shortUrl = restTemplate.postForObject("https://www.googleapis.com/urlshortener/v1/url", request, LinkedHashMap.class); return shortUrl.get("id"); } }
I didn't worry too much about validating that the string passed in was a URL for the time being as I always had control of that, but that should be something that would need to be considered.
No comments:
Post a Comment