function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ATLForceATLForce 

Help with Rest API

Hi everyone, 

 

I'm need help with the rest api. I need to create a new record in another org. For example on a visualforce page, I can select an account record and click submit and it will create that  account record in another org. I found the codes below for pulling record. However, I need to be able to insert new record to a different org. Any suggestion or sample codes will be great thank.

 

 

 

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 List<Contact> conlist{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;} 
    public List<apexclass> apexlist{get;set;}

    public FetchAccount()
    {
        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://' + LOGIN_DOMAIN + '.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 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.body,a.name From Apexclass a limit 10');
        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();

        apexlist = (List<apexclass>) parser.readValueAs(List<apexclass>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }

}

 

hareesh nhareesh n

am also faceing same problem

 

apex page

========================================================

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';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.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 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.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';
        }

    }
}
vfpage
-------------------------------------------------------------------------------------------------

<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<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="{!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:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>