Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Salesforce apex service to make http callout to Bitly url shortener service. The .java extension is just for syntax highlighting, save them as .cls in your project.
/**
* Simple service to make http callout to Bitly url shortener service.
*/
public class BitlyService {
/**
* Given a long URL will return the shortened version.
* https://dev.bitly.com/api-reference#createBitlink
*/
public String shorten(String url) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Bitly/v4/shorten');
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer {!$Credential.Password}');
req.setHeader('Accept', 'application/json');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'group_guid' => '{!$Credential.UserName}',
'long_url' => url
}));
HttpResponse res = new Http().send( req );
Map<String, Object> response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) response.get('link');
}
}
@douglascayers
Copy link
Author

douglascayers commented Feb 13, 2016

@douglascayers
Copy link
Author

douglascayers commented Jan 7, 2021

Code updated to use Bitly's API v4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment