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
mddean17mddean17 

Http callouts and cookies using Apex

Hi,
 
I have an urgent issue. The goal is to update the current user's profile via Apex. Since I can't do this as myself, I make an HTTP callout and log into the Web service API as another user. In principle this should work, and my code is below.
 
The problem is that the sid session cookie is not recognized when I call the myApexPage page and I get a redirect back to the login Url. Are there issues around passing cookie headers using Apex? Is sid not the right cookie name? I've tried setting the cookie domain and path properties but this doesn't help.
 
Any help is very much appreciated.
 
 
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://na5.salesforce.com/?un=username&pw=123456&loginType=');
HttpResponse res = h.send(req); 
string loc = res.getHeader('Location');
if (loc.indexOf('sid=') > -1)
{
            string sid = loc.substring(loc.indexOf('sid=')+4, loc.indexOf('je=')-1);
            req = new HttpRequest();
            req.setMethod('GET');
            req.setEndpoint('https://na5.salesforce.com/apex/myApexPage');
            req.setHeader('Cookie','sid='+sid);
            req.setHeader('Cookie','session_id='+sid);
            res = h.send(req);
           
            system.debug('Response: '+res.getBody());
}
SuperfellSuperfell
Why are you trying to screen scape an apex page, use an apex web service, or the regular api if you want to do something programatically.
mddean17mddean17

But if I could do these readily I would.

 

So I create an Apex web service but how do I log in as another user and invoke it? I can redirect to an scontrol, log in and call execute but I end up with the credentials on the page and this is a public PRM. If I could call the Web Service API via Apex I'd do this, but the Soap syntax isn't documented and it could days to get this right.

 

If anyone can help with this I'd really appreciate it, thanks.

 

cheenathcheenath

    req.setHeader('Cookie','sid='+sid);
    req.setHeader('Cookie','session_id='+sid);

You have two calls to setHeader with same key. Second call will just over write the first value.
Is that what you want?



DeepakKapoor81DeepakKapoor81

HI Dean,

 

Can you please share the code which you used to fix it,actually I hv the same requirement and could nt succesfully ablr to implememnt.

DeepakKapoor81DeepakKapoor81

Hi Dean, Can you please let me know how you had done this finally.Could you please share the code.

DeepakKapoor81DeepakKapoor81

Hi Dean,

 

Can you please help me?

Jia HuJia Hu
I can login and access the VF page with this method, but cannot really retrieve the data of VF page.

Does anyone know this?