Monday, 11 August 2014

Getting record from other Salesforce organization Using Apex and SOAP Web Service API

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.
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”
  1. https://www.salesforce.com
  2. https://ap1.salesforce.com

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


Apex Code:

1public with sharing class FetchAccount {
2
3    //Login Domain May be test, prerellogin.pre
4    String LOGIN_DOMAIN = 'www';
5    public String pwd{get;set;}
6    public String userName{get;set;}
7    public List<Account> acc{get;set;}
8    public String errMsg{get;set;}
9    public String displayError{get;set;}
10
11    public FetchAccount()
12    {
13        displayError = 'none';
14    }
15
16    public void fetch()
17    {
18        errMsg  = 'Some error occurred, please try again';
19        try
20        {
21        //-----------------------------------
22        // Login via SOAP/XML web service api
23        //-----------------------------------
24        HttpRequest request = new HttpRequest();
25        request.setEndpoint('https://' + LOGIN_DOMAIN +'.salesforce.com/services/Soap/u/22.0');
26        request.setMethod('POST');
27        request.setHeader('Content-Type''text/xml;charset=UTF-8');
28        request.setHeader('SOAPAction''""');
29        //not escaping username and password because we're setting those variables above
30        //in other words, this line "trusts" the lines above
31        //if username and password were sourced elsewhere, they'd need to be escaped below
32        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>');
33        Dom.XmlNode resultElmt = (newHttp()).send(request).getBodyDocument().getRootElement()
34          .getChildElement('Body','http://schemas.xmlsoap.org/soap/envelope/')
35          .getChildElement('loginResponse''urn:partner.soap.sforce.com')
36          .getChildElement('result''urn:partner.soap.sforce.com');
37
38        //-------------------------------
39        // Grab session id and server url
40        //--------------------------------
41        final String SERVER_URL = resultElmt.getChildElement('serverUrl','urn:partner.soap.sforce.com') .getText().split('/services')[0];
42        final String SESSION_ID = resultElmt.getChildElement('sessionId','urn:partner.soap.sforce.com') .getText();
43
44        //----------------------------------
45        // Load first 10 accounts via REST API
46        //---------------------------------
47        final PageReference theUrl = new PageReference(SERVER_URL +'/services/data/v22.0/query/');
48        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
49        request = new HttpRequest();
50        request.setEndpoint(theUrl.getUrl());
51        request.setMethod('GET');
52        request.setHeader('Authorization''OAuth ' + SESSION_ID);
53
54        String body = (new Http()).send(request).getBody();
55
56        JSONParser parser = JSON.createParser(body);
57
58        do{
59            parser.nextToken();
60        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
61
62        parser.nextToken();
63
64        acc = (List<Account>) parser.readValueAs(List<Account>.class);
65        }
66        catch(Exception e)
67        {
68            displayError = 'block';
69        }
70
71    }
72}

Visualforce Code:

1<apex:page controller="FetchAccount" standardStylesheets="true">
2<style type="text/css">
3.errorMsg{
4    font-size:0.8 em;
5    color:red;
6}
7</style>
8<apex:pageBlock >
9<apex:form >
10<apex:outputLabel value="UserName : " for="userName"/>
11<apex:inputText required="true" id="userName" value="{!userName}" />
12<br />
13<apex:outputLabel value="Password : " for="pwd"/>
14<apex:inputsecret id="pwd" value="{!pwd}"/>
15<br />
16<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}"rerender="wrapper" status="waitStatus" />
17<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
18<hr />
19<apex:outputPanel id="wrapper">
20<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
21<apex:pageBlockTable value="{!acc}" var="account" id="accTable"rowClasses="odd,even" styleClass="tableClass">
22 
23    <apex:column >
24        <apex:facet name="header">Account Name</apex:facet>
25         <apex:outputText value="{!account.name}"/>
26    </apex:column>
27 
28    <apex:column >
29        <apex:facet name="header">Created By</apex:facet>
30         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
31    </apex:column>
32 
33    <apex:column >
34        <apex:facet name="header">Phone</apex:facet>
35         <apex:outputText value="{!account.Phone}"/>
36    </apex:column>
37 
38</apex:pageBlockTable>
39</apex:outputPanel>
40</apex:form>
41</apex:pageBlock>
42</apex:page>

No comments:

Post a Comment