6.1 CookieManager

As you already know, the http server can send cookies along with the response, and you will need to work with them. Or vice versa, the http server is waiting for the client to send it Cookies and you need to add them to your http request. Of course, you can do this directly through the headers (handlers), but HttpClient offers you a more convenient mechanism - the CookieHandler. You can get it using the cookieHandler(). Example:

HttpClient client = HttpClient.newBuilder( URI.create("https://codegym.cc")).build();
CookieHandler handler = client.cookieHandler();

CookieHandler is an abstract class, so it's common to work with its CookieManager implementation. Which, in turn, has only a couple of methods through which you can get the CookieStore object. You can work with it in the future:

HttpClient client = HttpClient.newBuilder( URI.create("https://codegym.cc")).build();
CookieHandler handler = client.cookieHandler();
CookieManager manager = (CookieManager) handler;
CookieStore store = manager.getCookieStore();

CookieStore is an interface that has the following methods:

  • add()
  • get()
  • getCookies()
  • remove()
  • removeAll()

I won't go through them in detail, we've already covered HttpClient in detail. If suddenly you really need it, then the documentation on the CookieManager class can be found at the links:

Class CookieManager

CookieManager Class in Java

Custom CookieManager