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
gitguygitguy 

@Future and OAuth : [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

My client's application is /mostly/ callouts.  In one case, we actually do have a SF object we'd like to post chatter to.

 

I don't want the chatter message (another callout) slowing-down response time so I tried prefixing @future (callout=true).  You'll see in the code below it's a straightforward class.

 

Without @future, the post works fine but response time is impacted.  If I add @future I get the response, [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}], followed by that obnoxious "You have uncommitted..." nonsense (there is no DML in the debug log and only one SOQL execute).

 

Is there a simple solution to this?

 

public class Cheep {
    @future (callout=true) public static void PostMessage(string anId, string message)
    {
        message = message.replaceAll('\n', '\\\\n');
        
        PostMessageTo(
            URL.GetSalesforceBaseURL().toExternalForm() + '/services/data/v23.0/chatter/feeds/record/' + anId + '/feed-items', 
            message
        );    
    }    
    
    static void PostMessageTo(string location, string message)
    {
        HttpRequest req = new HttpRequest();
        Http http = new Http();
        req.setEndpoint(location);    
        req.setMethod('POST');
        req.setHeader('Authorization', 'OAuth ' + userInfo.getSessionId());
        req.setHeader('Content-Type', 'application/json');
        req.setBody('{ "body" : { "messageSegments" : [{"type": "Text","text" : "' + message + '"}]}}');

        try {         
            system.debug(req.getBody()); 
            HTTPResponse resp = http.send(req);            
            
            if (resp.getStatusCode() == 302)
                PostMessageTo(resp.getHeader('Location'), message);            
            else    
                system.debug(resp.getBody());
        }
        catch (Exception ex)
        {
            system.debug('Exception thrown : ' + ex.getMessage());
        }
    }    
}