[SalesForce] How to get salesforce instance url

To access chatter rest api using APEX code, I need salesforce instance server url in following format:

https://na17.salesforce.com

Is there any method which works in all cases

Case 1: Any Development Org

Case 2: My Domain Enabled

Case 3: Sandbox

Case 4: Managed Package

Best Answer

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();
Related Topic