Stat Tracker

Monday, March 21, 2011

Retrieve Salesforce / Force.com Server URL in Apex Code

Update - As of Summer 11 release this past weekend, you can now use the System.URL class to retrieve this information from a Trigger, Batch Apex, ETC. So this blog post is no longer valid if you use version 22 or later (which you should!). 

Checkout this link for the information:

http://blog.sforce.com/sforce/2011/05/one-of-the-trends-i-have-noticed-in-the-past-few-releases-is-an-even-greater-emphasis-on-openness-on-the-forcecom-platform.html


If you want to retrieve the Server URL in Apex code on the Force.com platform, you can use the following line of code in an Apex class:

ApexPages.currentPage().getHeaders().get('Host')

The only problem with this approach is that you can't get to the URL if you are in a Trigger or Apex Batch job.

If you need the Server URL in a non-request context peice of Apex code (Trigger, Batch Job, ETC) than I suggest using Custom Settings. You create a custom setting, and you can call it "Server Config" or something similar. Then, one time only, when you first create the environment, you manaully populate a string field on the Custom Setting and call it something like "Server URL" where you paste the URL from the address bar in your browser.

Then in all your custom Apex code, you can just retrieve the Server URL from your Custom Setting.

Its the most pain-free method I know of doing it.