-
-
Save Deepak-K-Anand/bf8f79b3aa63c193ad6e to your computer and use it in GitHub Desktop.
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
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