You need to sign in to do that
Don't have an account?

bit.ly Integration
I needed a way to shorten URLs I'm including in outgoing emails, so I wrote a quickie integration to bit.ly. Public domain... Hope it helps.
/*
Class to connect to bit.ly 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('http://api.bit.ly/shorten?version=2.0.1&format=xml&login='+LOGIN+'&apiKey='+APIKEY+'&longUrl='+EncodingUtil.urlEncode(url, 'UTF-8'));
request.setMethod('GET');
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**** bit.ly 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') {
reader.next();
shortUrl = reader.getText();
break;
}
if (reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'errorMessage') {
reader.next();
if (reader.getEventType() != XmlTag.END_ELEMENT) {
String errorMessage = reader.getText();
System.debug('\n* Error message from bit.ly: '+errorMessage);
return null;
}
}
reader.next();
}
return shortUrl;
}
private static testMethod void testBitly0() {
bitly.shorten('http://www.salesforce.com/');
}
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[http://www.salesforce.com]]></nodeKey><shortUrl>http://bit.ly/15pXjJ</shortUrl></nodeKeyVal></results><statusCode>OK</statusCode></bitly>';
XmlStreamReader reader = new XmlStreamReader(responseXml);
Test.startTest();
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);
Test.startTest();
String shortUrl = parseResponse(reader);
System.assertEquals(null, shortUrl);
}
}
Thanks for your post.
I'm trying to use bit.ly 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 bit.ly or bit.ly 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?
Thanks
Swapna