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
paul-lmipaul-lmi 

Preserving HTTP session state with successive callouts

I was wondering how we can leverage Apex to interact with a web service that requires session state (ie, cookies) to be preserved in order to issue further API calls.

 

I thought simply reusing the HTTP object would do this, but apparently not.  Here's what I have:

 

string endpoint = 'https://somesite.com/api'; string user = 'someuser'; string pwd = 'somepassword'; //set up the http object to be reused http ohttp = new http(); //set up the first request httprequest oReq1 = new httprequest(); oReq1.setendpoint(endpoint + 'login.aspx?user=' + user + '&pwd=' + pwd); oReq1.setmethod('GET'); httpresponse loginresponse = ohttp.send(oReq1); //set up the second request httprequest oReq2 = new httprequest(); oReq2.setendpoint(endpoint + 'secondapicall.aspx'); oReq2.setmethod('GET'); //this one fails because the session state is not preserved from the first call httprespons secondresponse = ohttp.send(oReq2);

 


 

 

Best Answer chosen by Admin (Salesforce Developers) 
ryanhcaryanhca

I don't see a way to do this easily with the API itself, so you probably have to code it yourself.

 

You'll have to parse the response headers for the cookie data, save that, then send it back with the subsequent request(s).

 

The initial response header should include one or more of the following lines:

 

Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME

 

Later response headers will need to include the following to send it back:

 

Cookie: NAME1=VALUE1;NAME2=VALUE2

 

 

 

 

All Answers

ryanhcaryanhca

I don't see a way to do this easily with the API itself, so you probably have to code it yourself.

 

You'll have to parse the response headers for the cookie data, save that, then send it back with the subsequent request(s).

 

The initial response header should include one or more of the following lines:

 

Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME

 

Later response headers will need to include the following to send it back:

 

Cookie: NAME1=VALUE1;NAME2=VALUE2

 

 

 

 

This was selected as the best answer
SuperfellSuperfell
You'll have to read the set-cookies header from the response of the first call, and add the relevant cookies header to the request of the 2nd call.
paul-lmipaul-lmi

for anyone reading this after, it'd be something like this

 

httpresponse hres = http.send(hReq);

String cookie = hres.getHeader('Set-Cookie');

 

and then use

 

hReq2.setHeader('Cookie: ' + cookie);

 

in the next/subsequent request.

Cristela HernandezCristela Hernandez
Thank you so much. You helped to fix my problem of consecutive requests to an external system.