Getting record from other Salesforce organization OR communication between multiple salesforce organization

Calling Rest Web service using Apex – Getting record from other Salesforce organization or Account or communication between multiple salesforce organization

In this article, I will explain the code which can be used for connecting and getting the records from different or multiple salesforce organization using Apex and REST Service.

Note : Here is new article to connect two salesforce instances in just 5 lines of code using Named Credentials.

To start first we will need to authorize below two URL which can be accessed from salesforce environment.
This can be done from “Setup | Administration Setup | Security Controls | Remote Site Settings”

Salesforce Remote Site Setting
Salesforce Remote Site Setting

It is possible that you may need to change first URL it may be or

This application will prompt for the Username and Password of the other salesforce account and display the 10 records of the Account.

Connect Other Salesforce Account - Output Screen
Connect Other Salesforce Account – Output Screen

Apex Code:

public with sharing class FetchAccount {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'www';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public FetchAccount()
        displayError = 'none';

    public void fetch()
        errMsg  = 'Some error occurred, please try again';
        // Login via SOAP/XML web service api
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns=""><Header/><Body><login xmlns=""><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', '')
          .getChildElement('loginResponse', '')
          .getChildElement('result', '');

        // Grab session id and server url
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', '') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', '') .getText();

        // Load first 10 accounts via REST API
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        request = new HttpRequest();
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();

        JSONParser parser = JSON.createParser(body);

        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));


        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        catch(Exception e)
            displayError = 'block';


Visualforce Code:

<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
    font-size:0.8 em;
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!}"/>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>


Related posts