0

I am trying to connect one sf org to anaother. I am using the below class to initiate the call from command button. I copied session id of target org and hard coded here in the class which then worked. But for next time it expires.

Can anyone help me out how i can dynamically have the session id of source org, so that i need not to hard code it.

public class Apex_Rest_DemoController {

    public String response{get;set;}
    public String accName{get;set;}
    public String accPhone{get;set;}
    public String accWebsite{get;set;}

    public PageReference CreateAccount() {
        //find access token using Auth 2.0 
       String Access_Token = '00D28000000Heme!AQ8AQAFOnSjXlGvbNT9JXj5vcC2XjQyFtz8ls_x0IMmoDuX91WDLvb9j5qficiTwQpCGjTYIRCUOmvwQOlWvP2.0HPA3x9M.';

        Httprequest req=new httprequest();
        String domainName='ap2.salesforce.com';

        String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
        req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
        //req.setHeader('Authorization','Bearer '+Access_Token);
        //req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
        Http http = new Http();
        HTTPResponse res = http.send(req);
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        return null;
    }
}

Modified Code - I have modified my code. Now i trying to do SOAP call , then capturing the seesion id and using the sessionid to make the REST call.I am now getting sessionid invalid error.

public class Apex_Rest_DemoController {

        public String response{get;set;}
        public String accName{get;set;}
        public String accPhone{get;set;}
        public String accWebsite{get;set;}

        String LOGIN_DOMAIN = 'ap2';
        public String pwd = '###############################';
        public String userName = '########.########@###.com';

        public PageReference CreateAccount() {

        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', '""');
        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');
        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();

        system.debug('@@@@@@' + SESSION_ID);

        Httprequest req=new httprequest();
        String domainName='ap2.salesforce.com';
        String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
            req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        response=res.getbody();
        return null;

    }

}

Regards

3
  • you can go for String sessionid = UserInfo.getSessionId(); to dynamically retrieval of Session id
    – sfdev
    Jul 22, 2015 at 7:26
  • Hi sfdev, where to use String sessionid variable in the code.. Jul 22, 2015 at 7:31
  • Note this has also been posted here.
    – OrangeDog
    Sep 28, 2016 at 11:07

1 Answer 1

1

Hey i am using like as below:

public class AnalyticsAPIConnector{
    public static string runReportSync(string reportId){
        Http http = new Http();
        HttpRequest httpReq = new HttpRequest();
        HttpResponse httpRes = new HttpResponse();
        httpReq.setMethod('GET');
        httpReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        httpReq.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+ '/services/apexrest/StakkonForce/v1.0/MYCALL/getAccountRecords');
        httpRes = http.send(httpReq);
        return httpRes.getBody();
    }
}

and another observation from documentation says:

For the REST API, use an HTTP authorization header with the following format Authorization: Bearer Access_Token. For the SOAP API, the access token is placed in the SessionHeader SOAP authentication header. For the identity URL, use either an HTTP authorization header (as with the REST API) or use as an HTTP parameter oauth_token. so please check this as well. Thanks ...go crazy with code

2
  • Hi sfdev.. httpReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); will get the session id of current user logged in. How to get the sessionid of target org.. Do we need to pass uid, password of target org. If yes.. please share some sample. Jul 22, 2015 at 8:38
  • For getting sessionid of target sfdc org we need to pass clientid, client secret key, userid, password. But i am stuck as i dont know how to proceed. any help will be very much appreciated. Regards Jul 22, 2015 at 9:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .