+ Start a Discussion
Dippan PatelDippan Patel 

Get Salesforce Instance from APEX

Hi All, 

I want Salesforce instance name to add a remote site.
Below is my code: 
String host = URL.getSalesforceBaseUrl().getHost();
String server = host.split('\\.')[1];
String direct =  'https://' + server + '-api.salesforce.com';

I get proper server names such as CS10, CS94 in case of Developer orgs and production. 

However, in case of some sandboxes, I get server as visualforce.
 
Due to this the variable direct turns out to be https://visualforce-api.salesforce.com instead of https://yourdomain-api.salesforce.com

Not able to understand why? 
        
 
Best Answer chosen by Dippan Patel
Raj VakatiRaj Vakati
Its very easy 

use this code
 
String instanceName = [select InstanceName from Organization limit 1].InstanceName;

 

All Answers

Dippan PatelDippan Patel
P.S. This occurs for the Unlimited edition sandboxes. 
Raj VakatiRaj Vakati
Its very easy 

use this code
 
String instanceName = [select InstanceName from Organization limit 1].InstanceName;

 
This was selected as the best answer