Fetching data from another salesforce instance using API

Visualforce page:

<apex:page controller="SearchAcctFromSf" standardStylesheets="true">
<apex:form >

<apex:pageBlock >
    <apex:pageblockSection columns="2" >
        <apex:outputLabel value="UserName"/>
        <apex:inputText required="true" id="userName" value="{!userName}" />
        <apex:outputLabel value="Password"/>
        <apex:inputsecret id="pwd" value="{!pwd}"/>      
    </apex:pageblockSection>
    <apex:pageblockButtons >
        <apex:commandButton id="getRecords" value="Fetch" action="{!fetch}" rerender="acctDetails" status="waitStatus" />
    </apex:pageblockButtons>
</apex:pageBlock>

<apex:actionStatus startText="Fetching..." id="waitStatus"/>

<div style="display:{!displayError}"> {!errMsg} </div>

<apex:pageBlock >
    <apex:pageblockSection id="acctDetails">
        <apex:pageBlockTable value="{!acc}" var="account" id="accTable">
  
            <apex:column >
                <apex:facet name="header">Account Name</apex:facet>
                <apex:outputText value="{!account.name}"/>
            </apex:column>
  
            <apex:column >
                <apex:facet name="header">Created By</apex:facet>
                <apex:outputText value="{!account.CreatedBy.FirstName}"/>
            </apex:column>
  
            <apex:column >
                <apex:facet name="header">Phone</apex:facet>
                <apex:outputText value="{!account.Phone}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageblockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

Apex Controller:

public with sharing class SearchAcctFromSf {  
    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 SearchAcctFromSf() 
{
        displayError = 'none';
    }

    public void fetch() 
{
        errMsg  = 'Some error occurred, please try again';
        try {
        /*-----------------------------------
         Login via SOAP/XML web service api
        -----------------------------------*/
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://www.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        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="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        /*-------------------------------

         Grab session id and server url
        --------------------------------*/
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        /*----------------------------------

         Load first 20 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.Industry From Account a limit 20');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

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


        JSONParser parser = JSON.createParser(body);


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

        parser.nextToken();


        acc = (List<Account>) parser.readValueAs(List<Account>.class);

        }
        catch(Exception e) {
            displayError = 'block';
        }

    }

}

Remote Site settings:

Dont forget to add "http://www.salesforce.com" under Setup --> Administration Setup --> Security Controls --> Remote Site Settings.



Output:

15 comments:

  1. Its not working, neither i am getting error Nor the result.
    whats wrong?

    ReplyDelete
    Replies
    1. Check whether u hav records in ur org...

      Delete
    2. in which account it should create....reply

      Delete
    3. Don't forget to add "https://www.salesforce.com" in Remote site settings.

      Delete
  2. really it is not working can u please update it correctly

    ReplyDelete
    Replies
    1. Don't forget to add "https://www.salesforce.com" in Remote site settings.

      Cheers!!!

      Delete
    2. i had added remote site settings now also it is not working can you please provide me information

      Delete
    3. In remote site settings, don't forget to give your Salesforce instancs server url.

      For ap1, give https://ap1-api.salesforce.com

      cheers!!!

      Delete
    4. I have added this url (http://www.salesforce.com) to remote site settings,after clicking on feching button i am not getting account related records,what i do

      Delete
    5. It's Working fine.. Thanks for import the code..! endpoint URL and Remote site setting URL must be same then only it's work..!!

      Delete
  3. Can any one please share the Test class for the above code..
    Thanx in advance

    ReplyDelete
  4. not showing anything....................no output ..................pls post correct code

    ReplyDelete
    Replies
    1. If you see in User login history, the status is like "Failed: API security token required" So just provide your Security token with your password. Like Password is 'abc1234" and security token "pAAAAAXXXVVvzsFA0Bls9bC"then enter abc12334pAAAAAXXXVVvzsFA0Bls9bC

      Delete
  5. Getting Http Response like "System.HttpResponse[Status=Server Error, StatusCode=500]"
    Even SessionId was not generated for my Request. plz do the needful..

    ReplyDelete
  6. Hi... My login history status is " success ". End Point URL is setEndpoint('https://attributeit-dev-ed.my.salesforce.com/services/Soap/u/22.0'); and remote site url is " https://attributeit-dev-ed.my.salesforce.com ". but not fetching the account data. Please let me know the info which i need to change.

    ReplyDelete