Search code examples
springresthttpsessionresttemplate

Unable to Retrieve cookies when request is called using Spring RestTemplate


I have two web applications. There is a HttpSession at second application and first application knows the sessionid of it.

I am making a request from First application to second application using RestTemplate by adding its session id to headers.

When the request is received at the second application, I am trying to read all its cookies from request. But, I only see the JSESSIONID cookie and don't get all the cookies that I set previously.

Suppose, I access the same url on the browser manually, I see all those cookies retrieved.

Request made in First application:

String sessionId = "6iuvgwy5ceqzwlxh646qo0ms";//SessionId of second application
String url = "http://example.com/data/retrieve";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + sessionId);
HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, 
HttpMethod.GET, requestEntity, String.class);

If this can't be done using Spring RestTemplate, please suggest me if there is any other way of doing it.


Solution

  • There is no session cookie. Cookie is just a header. You lind of reset the header to have only JSESSIONID.

    To fix it change the logic a bit

    You somehow get the session id (I guess from some request). Get not only the session but all the rest cookie as well and add them to the requestHeaders when you call the restTemplate.