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

@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');
            URL.GetSalesforceBaseURL().toExternalForm() + '/services/data/v23.0/chatter/feeds/record/' + anId + '/feed-items', 
    static void PostMessageTo(string location, string message)
        HttpRequest req = new HttpRequest();
        Http http = new Http();
        req.setHeader('Authorization', 'OAuth ' + userInfo.getSessionId());
        req.setHeader('Content-Type', 'application/json');
        req.setBody('{ "body" : { "messageSegments" : [{"type": "Text","text" : "' + message + '"}]}}');

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