1. Overview

In this tutorial, we're going to look at how we can handle cookies using Apache HttpClient 4.

2. Handling Cookies

The CookieStore interface contains operations for managing the cookies. Moreover, Apache HttpClient provides a built-in implementation - BasicCookieStore.

To use BasicCookieStore, we must first initialize one and then pass the instance to HttpClient:

public void executePostAndListCookies() throws Exception {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) {
        
        // Implementation details
    }
}

As a result, HttpClient will store the cookies in this BasicCookieStore instance.

For example, we can list the cookies after performing an HTTP request:

private void performRequest(BasicCookieStore cookieStore, CloseableHttpClient httpClient, String url)
  throws URISyntaxException, IOException {
    HttpUriRequest getGoogle = RequestBuilder.get()
      .setUri(new URI(url))
      .build();
    try (final CloseableHttpResponse response = httpClient.execute(getGoogle)) {
        EntityUtils.consume(response.getEntity());
        List<Cookie> cookies = cookieStore.getCookies();
        cookies.stream().forEach(System.out::println);
    }
}

Here, we're using the previously created HttpClient instance. After we have the response, we're calling cookieStore.getCookies() and printing the cookie values.

The BasicCookieStore class also enables us to clear the cookies:

private void performRequestAndClearCookies(BasicCookieStore cookieStore, CloseableHttpClient httpClient, String url)
    // Implementation details

    try (final CloseableHttpResponse response = httpClient.execute(getGoogle)) {
        EntityUtils.consume(response.getEntity());
        cookieStore.clear();
    }
}

3. Summary

In this tutorial, we've looked at how we can store and manage cookies using Apache HttpClient 4.

Check out the source code for all examples over on Github.