Search code examples
springspring-bootcookies

Is there a way to get the cookies from one restTemplate exchange response and set it to another separate request?


I am relatively new to Spring and Spring Boot and need some much-needed help.

I am working on a project where I need to take the cookies I receive from one restTemplate response and pass them on to another request.

The code looks something like this:

ResponseEntity<SomeObject> responseOne  = restTemplate.exchange(URL, HttpMethod.POST, request, SomeObject.class);

There are 3 cookies in total and I need them to move from responseOne to included in the call of responseTwo.

ResponseEntity<SomeOtherObject> responseTwo  = restTemplate.exchange(URL, HttpMethod.POST, request, SomeOtherObject.class);

Hope someone can help!


Solution

  • You can access the cookies from the responseOne.getHeaders() method. They are sent as headers with name Set-Cookie e.g.:

    Set-Cookie: JSESSIONID=4054C174E5CD78D5FDD8BD8D155FC233; Path=/yourapp; Secure; HttpOnly Set-Cookie: anotherCookie=anotherValue; path=/; HttpOnly

    Parse each header value to separate the cookie name and the cookie value.

    Then you just need to set them in the request entity of the second call:

    
    SomeObject someObject = ...
    
    HttpHeaders headers = new HttpHeaders();
    headers.add("COOKIE", "JSESSIONID=4054C174E5CD78D5FDD8BD8D155FC233; anotherCookie=anotherValue; cookie3=value3");
    
    HttpEntity<SomeObject> entity = new HttpEntity<>(someObject, headers);
    
    ResponseEntity<SomeOtherObject> responseTwo  = restTemplate.exchange(URL, HttpMethod.POST, request, SomeObject.class);