[SalesForce] Rest call with same salesforce org – [Status=Unauthorized, StatusCode=401]

Can some one please guide me where I am going wrong. For some reason i have to invoke the same instance. But i am getting

[Status=Unauthorized, StatusCode=401]

Error when I Debug.

public class FetchAccountUsingREST{

    public FetchAccountUsingREST(){

    }    
    public void onLoadActionMethod(){
        //get all list views

        httpRequest req = new HttpRequest();
        httpResponse resp = new HttpResponse();
        http httpMeth = new http();
        //String oAuthtt = 'Bearer' + UserInfo.getSessionID();

From Winter 2017, Salesforce has removed session ID. So Created one Dummy VFP and ran this chunk to get the session ID. If I Debug UserInfo.getSessionID(), It shows SESSION_ID_REMOVED

<apex:page>
    {!$Api.Session_ID}
</apex:page>

Later i passed the same session id in my controller.

        String oAuthtt = ' Bearer' + '00D90000000*********************glGTC4hC1YiEirY7FSeOFPmS17SXbIWzwFZGHTTY5Hre8Je40Zwas3o9P9N';
        req.setMethod('GET');
        req.setHeader('Authorization', oAuthtt );
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint('https://ckdomaintest-dev-ed.my.salesforce.com/services/data/v41.0/sobjects/Account/listviews');

        try{

            resp = httpMeth.send(req);
            system.debug('resp >>'+resp);

        }catch(Exception e){
            system.debug('Exception >>'+e.getMessage());
        }
    }
}

I can do it other ways using Connected and Named Credentials, but I am curious to see where i am going wrong on this.

Best Answer

You don't need the Visualforce page. UserInfo.getSessionID() still works, you just cannot System.debug() a session ID - the logs will show SESSION_ID_REMOVED.

Your 401 error usually indicates that you have not created a Remote Site Setting for the instance your code is running on. Make sure to create a Remote Site Setting for https://ckdomaintest-dev-ed.my.salesforce.com to allow REST access from within the same instance.

You appear to be missing a space between 'Bearer' and the Session ID in your authorization header.