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
Force.comForce.com 

Bitly (Url Shortening) Integration with Salesforce

I want to embed javascript coding in visualforce. The javascript coding is for integrating 'Bitly' platform with salesforce.

 

My visualforce code is:

 

<apex:form >
<apex:inputText value="{!Candidate__c.Long_Url__c}" id="theText" onclick="javascript&colon;go('{!$Component.theText}')" ></apex:inputText>

  <script type="text/javascript" src="/js/functions.js"></script>
    <script src="/soap/ajax/11.1/connection.js"></script>
    
   <script language="javascript">
    
   function go(f) {
    var theText = document.getElementById(f).value;
   alert(theText);
   }
var xhr = new XMLHttpRequest(); 

xhr.open("GET", "http://api.bitly.com//v3/shorten?login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e&longUrl="+theText);

xhr.onreadystatechange = function(){ 

alert('test');
if(xhr.readyState == 4) { 
if(xhr.status==200) { 
var jsonResponse = JSON.parse(xhr.responseText);
var bitlyUrl = jsonResponse.data.url; 

myFunc(bitlyUrl);
var t = xhr.send();
}
}
}

</script>
</apex:form>
<apex:form >
<apex:actionFunction name="myFunc" action="{!field}">
<apex:param name="param1" value=""/>
</apex:actionFunction>
</apex:form>

</apex:page>

 

Bitly is used for URL shortening. I want the shortened url to be passed to the controller through <apex:actionfunction>.

 

Please help. Its really urgent. I am completely stuck.

 

Thanks

 

 

Best Answer chosen by Admin (Salesforce Developers) 
BritishBoyinDCBritishBoyinDC

Not sure how to approach this via javascript, but this code works if you create a class, set up the remote site, and call it using the code at the bottom - so you could pass a URL into this class, and get back the string in the controller...

 

I would probably rework the XML read method to use the DOM functionality, and I typically store the login/api credentials somewhere else (e.g. a custom setting) but I tried this in my dev org, and it works fine...

 

 

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();     }
   else
   {
   String str = '<bitly><results shortUrl="http://bit.ly/QqHEm">Foo bar</results></bitly>';
   reader = new XmlStreamReader(str);
   }
   return readXMLResponse(reader,'shortUrl');
  
}


public static HttpRequest buildWebServiceRequest(String purl){
String endpoint;
            HttpRequest req = new HttpRequest();
            endpoint = 'http://api.bit.ly/shorten?version=2.0.1&format=xml&history=1&longUrl=' + purl + '&login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e';
            req.setEndpoint(endpoint); 
            req.setMethod('GET');
            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
    system.debug(reader.toString());
    while(reader.hasNext()) {
            if (reader.getEventType() == XmlTag.START_ELEMENT) {
                           if (reader.getLocalName() == sxmltag) {
                              reader.next();
                                  if (reader.getEventType() == XmlTag.characters) {
                                           retValue = reader.getText();    
      }
      }
      }
      reader.next();
    }
return retValue;
}

        
}

 

bitly b = new bitly();
b.mode = 'live';
b.sUrl = 'http://www.bridgefarmconsulting.com';

system.debug('Check BitLy' + b.getbitly() );

 

 

 

All Answers

BritishBoyinDCBritishBoyinDC

Not sure how to approach this via javascript, but this code works if you create a class, set up the remote site, and call it using the code at the bottom - so you could pass a URL into this class, and get back the string in the controller...

 

I would probably rework the XML read method to use the DOM functionality, and I typically store the login/api credentials somewhere else (e.g. a custom setting) but I tried this in my dev org, and it works fine...

 

 

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();     }
   else
   {
   String str = '<bitly><results shortUrl="http://bit.ly/QqHEm">Foo bar</results></bitly>';
   reader = new XmlStreamReader(str);
   }
   return readXMLResponse(reader,'shortUrl');
  
}


public static HttpRequest buildWebServiceRequest(String purl){
String endpoint;
            HttpRequest req = new HttpRequest();
            endpoint = 'http://api.bit.ly/shorten?version=2.0.1&format=xml&history=1&longUrl=' + purl + '&login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e';
            req.setEndpoint(endpoint); 
            req.setMethod('GET');
            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
    system.debug(reader.toString());
    while(reader.hasNext()) {
            if (reader.getEventType() == XmlTag.START_ELEMENT) {
                           if (reader.getLocalName() == sxmltag) {
                              reader.next();
                                  if (reader.getEventType() == XmlTag.characters) {
                                           retValue = reader.getText();    
      }
      }
      }
      reader.next();
    }
return retValue;
}

        
}

 

bitly b = new bitly();
b.mode = 'live';
b.sUrl = 'http://www.bridgefarmconsulting.com';

system.debug('Check BitLy' + b.getbitly() );

 

 

 

This was selected as the best answer
Force.comForce.com

Thanks a lot. I can now call the Bitly platform through salesforce.

 

Thanks

streetstreet

Im working on same functionality.

 

Using the same code what u have posted.

 

im getting this error:

Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.bit.ly/shorten?version=2.0.1&format=xml&history=1&longUrl=http://flourish.sandbox1.cs7.force.com&login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e

 

An unexpected error has occurred. Your development organization has been notified.

 

what to be changed for endpoint, in bitly class??

 

 

 

 

BritishBoyinDCBritishBoyinDC

You'll need to add the Bitly URL to your Remote Sites...

 

Go to Security Controls, Remote Site Settings and add http://api.bit.ly as an authorized site...

streetstreet

I have added its working fine.

tgeissetgeisse

Just out of curiosity, what would be the advantage of changing the APEX code above to using DOM parsing?

BritishBoyinDCBritishBoyinDC

I was running the code in a batch process (i.e. no UI) - so I needed the values in an Apex format that I could then append to records.

Derek Davis 18Derek Davis 18
I am getting the following error:

"Error: Compile Error: line 32:118 no viable alternative at character '"' at line 32 column 118"

Below is Line 32. I attempted removing the " symbol, but it only led to more errors.
endpoint = '<a rel="nofollow" href="http://api.bit.ly/shorten?version=2.0.1&format=xml&history=1&longUrl='" target="_blank">http://api.bit.ly/shorten?version=2.0.1&format=xml&history=1&longUrl='</a> + purl + '&login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e';

Any suggestions?
 
kj007kj007
I want to integrate salesforce with bitly. With this integration need to generate short url from salesforce and track the summary (like clicks, location etc,.) of short url in salesforce.with new version of bitly v4.