By default, JDK 11's HTTP Client supports cookies, but there are instances where built-in support is disabled. We can enable it as follows:
HttpClient client = HttpClient.newBuilder()
.cookieHandler(new CookieManager())
.build();
So, the HTTP Client API allows us to set a cookie handler using the HttpClient.Builder.cookieHandler() method. This method gets an argument of the CookieManager type.
The following solution sets CookieManager that doesn't accept cookies:
HttpClient client = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
For accepting cookies, set CookiePolicy to ALL (accept all cookies) or ACCEPT_ORIGINAL_SERVER (accept cookies only from the original server).
The following solutions accept all cookies and display them in the console (if any credentials are reported as invalid, then consider obtaining a new token from https://gorest.co.in/rest-console.html):
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
HttpClient client = HttpClient.newBuilder()
.cookieHandler(cm)
.build();
HttpRequest request = HttpRequest.newBuilder()
.header("Authorization",
"Bearer mT8JNMyWCG0D7waCHkyxo0Hm80YBqelv5SBL")
.uri(URI.create("https://gorest.co.in/public-api/users/1"))
.build();
HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println(" Body: " + response.body());
CookieStore cookieStore = cm.getCookieStore();
System.out.println(" Cookies: " + cookieStore.getCookies());
Checking the set-cookie header can be done as follows:
Optional<String> setcookie
= response.headers().firstValue("set-cookie");