Skip to content

Instantly share code, notes, and snippets.

@Deepak-K-Anand
Last active December 14, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deepak-K-Anand/bf8f79b3aa63c193ad6e to your computer and use it in GitHub Desktop.
Save Deepak-K-Anand/bf8f79b3aa63c193ad6e to your computer and use it in GitHub Desktop.
global class GoogleUrlShortener
{
webservice static string shortenUrl(string longUrl)
{
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse httpRes = new HttpResponse();
String body='';
httpReq.setMethod('POST');
httpReq.setHeader('Content-Type', 'application/json');
httpReq.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=<YOUR-API-KEY-HERE>');
body = '{\"longUrl\": \"' + longUrl + '\"}';
httpReq.setHeader('Content-Length', String.valueOf(body.length()));
httpReq.setBody(body);
try{
httpRes = http.send(httpReq);
String shortUrl = parseJSON(httpRes.getBody(), 'id');
return shortUrl;
}
catch(Exception e){
System.debug('Class: GoogleUrlShortener; ' + 'Method: (WS)ShortenUrl; Message: ' + e.getMessage());
return 'Error';
}
}
private static string parseJSON(String jsonText, String node)
{
JSONParser parser = null;
parser = JSON.createParser(jsonText);
while (parser.nextToken() != null)
{
if(parser.getText()==node)
{
parser.nextToken();
return parser.getText();
}
}
return 'Error';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment