Java REST Client POST with Cookie

In previous post I showed how to get cookie from server response with RestTemplate and exchange method.

In this article we will use that cookie in order to call other server API GetUsers.

private void postMethodWithCookie(String secret) {
	
	final String url = "http://codeflex.co:8080/rest/Management/getUsers";

	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.add("Cookie", "credentials=" + secret);

	HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
	
	ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Users.class);
	Users users = (Users) response.getBody();
	
}

As you can see from the code above, first we creating HttpHeader with our given secret key, then we adding it to the HttpEntity and finally calling HTTP exchange method. In case if the secret key is correct server will return the list of users in response.

LEAVE A REPLY