Monday, November 28, 2011

Fetching Remote Data in Salesforce.com using APEX

Suppose you need to fetch some data from a remote website inside a Salesforce.com APEX Code. This can be any type of text ranging from text to XML content, which you want to use to perform additional tasks based on. This comes in particularly handy if you need to do some sort of an integration with a Legacy System which cannot produce a structured WSDL Web Service.

Here is how you can accomplish this:

1. Create an APEX Class called "HttpCalloutSample", with the following code:


Now let's call this APEX Class using Eclipse Force.com IDE "Execute Anonymous" code block feature (or if you prefer to call it from within an APEX Trigger you can do that too). Your calling code would look something like this:


The URL is basically the URL of the content you wish to fetch from the Remote Server. In this case I am using the URL of the Distribution Agreement of one of my open source projects, which is a simple text file containing some text. The first time you execute the code, you will see this error:

This is because by default Salesforce.com blocks accessing remote websites. We can fix this by going to "Setup > Security Controls > Remote Site Settings" in Salesforce, and add an Exception for our Remote site:

Now when you call that same site URL again, you will be able to access the remote content and fetch the data from it. If you look in your debug log, you will see an entry like this:

10:15:31.238 (238577000)|USER_DEBUG|[5]|DEBUG|Definition of Freeware

Freeware distribution gives users a chance to try software and continue to us ... (the rest of the content)


I hope others find this blog entry helpful.

Thanks,
Pete Soheil
DigiOz Multimedia, Inc.
www.digioz.com

No comments: