How to get salesforce instance url

You are looking for URL.getSalesforceBaseUrl().

Edit

The Winter 19 release is introducing another method to get the URL, which will give you the canonical URL for your org: URL.getOrgDomainUrl().

Returns the canonical URL for your org. For example, https://yourDomain.my.salesforce.com or, for orgs without My Domain enabled, https://yourInstance.salesforce.com.


Both of the above methods return a System.URL. If you would like the string version, simply call .toExternalForm() on that instance. For example:

String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();

To retrieve a URL object containing the full beginning portion of the URL, such as "https://na17.salesforce.com", you may use the static method:

    System.URL.getSalesforceBaseURL();  // Yields URL object for https://xxxx.salesforce.com

As Ashish notes above, suffixing this method with ".toExternalForm()" will convert the URL object into its text representation, as follows:

    System.URL.getSalesforceBaseURL().toExternalForm();  // Yields string "https://xxxx.salesforce.com"

Furthermore, if you wish to retrieve only the subdomain portion of the URL (the "na17" part to the left of the ".salesforce.com" domain), use:

    System.URL.getSalesforceBaseURL().getHost();  // Yields subdomain (host) as string

These methods will work reliably across Production, Sandboxes, Dev Orgs, etc. Which one you choose depends upon your specific need in the code that you are writing.

Lastly, if you're trying to create a host-independent object link, you may do so as follows:

    String link = '<a href="' + System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + sObject.Id + '" target="_blank">sObject Link</a>';

I used this approach to get just the instance, as in managed packages the other one approaching is not working for me

String urlInstance = String.valueof(System.URL.getSalesforceBaseURL()).replace('Url:[delegate=','').replace(']','');
String[] instance = urlInstance.split('\\.');
req.setEndpoint('https://'+instance[1]+'.salesforce.com/services/apexrest/cloudmobile/myservice/');

Hope it helps.

Tags:

Apex

Chatter