Java REST Client Get Cookie From Server Response

Sometimes in order to be able to perform some actions via REST API server wants the client to be logged in. It may be done by sending to the client some secret code in the response header.

In order to get header content we will use exchange method of RestTemplate of Spring framework.

Lets say in order to be logged in client must send username and password to the server. If username and password are correct then client will receive a secret code inside SET-COOKIE field of the response header. Our target is to fetch that code from the response. Here we go:

final String url = "http://codeflex.co:8080/rest/Management/login";
 
RestTemplate template = new RestTemplate();
Credentials cred = new Credentials();
cred.setUserName("admin@codeflex.co");
cred.setPassword("godmode");

HttpEntity<Credentials> request = new HttpEntity<>(cred);		
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
HttpHeaders headers = response.getHeaders();
String set_cookie = headers.getFirst(headers.SET_COOKIE);

System.out.println("Response: " + response.toString() + "\n");
System.out.println("Set-Cookie: " + set_cookie + "\n");
System.out.println("********* FINISH *******");

And this is the program output:

Response: <200 OK, {Server=[Apache-Coyote/1.1], Set-Cookie=[credentials=hrVfzvfE-7tQ1ZQlggsFwhsV_RGvKTRS2MRyAhUgHKU_#_HLSpmEMQkCl3rew0S6q3lg; Path=/], Content-Length=[0], Date=[Thu, 22 Sep 2016 03:58:23 GMT]}>

Set-Cookie: credentials=hrVfzvfE-7tQ1ZQlggsFwhsV_RGvKTRS2MRyAhUgHKU_#_HLSpmEMQkCl3rew0S6q3lg; Path=/

By the way Credentials is a simple class with name and password and the imports are following:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

Now when we have the cookie we may call other server APIs.

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.