[SalesForce] Is it possible to read cookie while doing a HTTP Get to external website

Well was wondering if this is possible at all ? The aim is to get a cookie from an external website.

But while going through the HTTP class for both Request and Response I don't think there is a method to access this cookie and I even looked into the response header and I wasn't able to find the value there.

Is there is a workaround to read the cookie ?

Best Answer

You can use response.getHeader('Set-Cookie') to find the cookies set by the responding site.

HttpRequest request1 = new HttpRequest();
request1.setMethod('GET');
request1.setEndpoint('http://www.google.com/');

HttpResponse response1 = new Http().send(request1);
String cookies = getResponse.getHeader('Set-Cookie'); //semicolon-delimited keys and values

Then you can transmit the same cookie in a subsequent request (eg to simulate a browser session)

HttpRequest request2 = new HttpRequest();
request2.setMethod('GET');
request2.setEndpoint('http://www.google.com/');
request2.setHeader('Cookie', cookies);

HttpResponse response2 = new Http().send(request2);
Related Topic