function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ryanhcaryanhca Integration

I needed a way to shorten URLs I'm including in outgoing emails, so I wrote a quickie integration to Public domain... Hope it helps.



Class to connect to API to shorten a long URL
global class bitly {
private static final String APIKEY = 'your_api_key';
private static final String LOGIN = 'your_bit.ly_login';

global static String shorten(String url) {
Http h = new Http();
HttpRequest request = new HttpRequest();
request.setEndPoint(''+LOGIN+'&apiKey='+APIKEY+'&longUrl='+EncodingUtil.urlEncode(url, 'UTF-8'));

try {
HttpResponse response = h.send(request);

if (response.getStatusCode() == 200) {
XMLStreamReader reader = response.getXmlStreamReader();
String shortUrl = parseResponse(reader);
return shortUrl;
} catch (System.CalloutException e) {
System.debug('\n**** CalloutException: '+e);

// if the callout was unsuccessful for any reason
return null;

private static String parseResponse(XmlStreamReader reader) {
String shortUrl;
while (reader.hasNext()) {
if (reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'shortUrl') {;
shortUrl = reader.getText();

if (reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'errorMessage') {;
if (reader.getEventType() != XmlTag.END_ELEMENT) {
String errorMessage = reader.getText();
System.debug('\n* Error message from '+errorMessage);
return null;

return shortUrl;

private static testMethod void testBitly0() {

private static testMethod void testBitly1() {
String responseXml = '<bitly><errorCode>0</errorCode><errorMessage></errorMessage><results><nodeKeyVal><userHash>15pXjJ</userHash><shortKeywordUrl></shortKeywordUrl><hash>M2FqH</hash><nodeKey><![CDATA[]]></nodeKey><shortUrl></shortUrl></nodeKeyVal></results><statusCode>OK</statusCode></bitly>';
XmlStreamReader reader = new XmlStreamReader(responseXml);
String shortUrl = parseResponse(reader);
System.assertNotEquals(null, shortUrl);

private static testMethod void testBitly2() {
String responseXml = '<bitly><errorCode>203</errorCode><errorMessage>You must be authenticated to access shorten</errorMessage><statusCode>ERROR</statusCode></bitly>';
XmlStreamReader reader = new XmlStreamReader(responseXml);
String shortUrl = parseResponse(reader);
System.assertEquals(null, shortUrl);




Message Edited by ryanhca on 10-13-2009 10:14 AM
Looks good! Nice job.

Thanks for your post.

I'm trying to use to shorten the URL's to fit the salesforce URL field.


I'm not sure which product i should be using for this? Is this the or Enterprise?

We will be using this technique very frequently so i dont want to hit any api limits.

Can you please share your experience using this product in salesforce?