Create Short URLs with Bitly


This post is related to how to integrate Salesforce and Bitly to create short urls to include in communication Messages.

Step 1. Sign-up for Bitly

To use the Bitly API you will need to register. You can sign-up using Twitter, Facebook, or create a new login with their service. I chose to create a Bitly specific login using below url.

Step 2. Create Bitly Apex Classes

I developed below class, that encapsulates the Bitly http callouts.

global class bitly
Public String mode;
Public String sUrl;

public string getbitly ()
String shorten;
XmlStreamReader reader;
HttpResponse res;

//First, build the http request
Http h = new Http();
HttpRequest req = buildWebServiceRequest(sURL);

//Second, invoke web service call
if (mode==’live’) { res = invokeWebService(h, req); }

if (mode==’live’) { reader = res.getXmlStreamReader(); }
String str = ‘Foo bar’;
reader = new XmlStreamReader(str);
return readXMLResponse(reader,’shortUrl’);

public static HttpRequest buildWebServiceRequest(String purl)
String endpoint;
HttpRequest req = new HttpRequest();
endpoint = ‘’+purl +’&history=1&login=BitlyAPPName&apiKey=R_42d58b4eda1c412b8ef30577442428e4’;
return req;

public static HttpResponse invokeWebService(Http h, HttpRequest req)
{ //Invoke Web Service
HttpResponse res = h.send(req);
return res;

public static String readXMLResponse(XmlStreamReader reader, String sxmltag)
{ string retValue;
// Read through the XML
if (reader.getEventType() == XmlTag.START_ELEMENT)
if (reader.getLocalName() == sxmltag)
if (reader.getEventType() == XmlTag.characters)
retValue = reader.getText();
return retValue;

Whenever you implement it you just need to change BitlyAPPName and apikey from endpoint.


For calling bitly class use below lines

bitly b = new bitly();

b.mode = ‘live’;

b.sUrl = ‘’;

system.debug(‘Check BitLy short url – ‘ + b.getbitly() );


You will output as “Check BitLy short url –

About the author

Nawal Bedmutha

Salesforce Developer

By Nawal Bedmutha