You need to sign in to do that
Don't have an account?

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);
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
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
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.