HttpClient 4 – Send Custom Cookie

1. Overview

This tutorial will focus on how to send a Custom Cookie using the Apache HttpClient 4.

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

2. Configure Cookie Management on the HttpClient

2.1. HttpClient After 4.3

In the newer HttpClient 4.3, we’ll leverage the fluent builder API responsible with both constructing and configuring the client.

First, we’ll need to create a cookie store and set up our sample cookie in the store:

BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);

Then, we can set up this cookie store on the HttpClient using the setDefaultCookieStore() method and send the request:

@Test
public void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    final HttpGet request = new HttpGet("http://www.github.com");

    response = client.execute(request);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

A very important element is the domain being set on the cookie – without setting the proper domain, the client will not send the cookie at all!

Also, depending on the exact version you use, you may also need to set:

cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

2.2. HttpClient Before 4.3

With older versions of the HttpClient (before 4.3) – the cookie store was set directly on the HttpClient:

@Test
public void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    DefaultHttpClient client = new DefaultHttpClient();
    client.setCookieStore(cookieStore);

    HttpGet request = new HttpGet("http://www.github.com");

    response = client.execute(request);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

Other than the way the client is built, there’s no other difference from the previous example.

3. Set the Cookie on the Request

If setting the cookie on the entire HttpClient is not an option, we can configure requests with the cookie individually using the HttpContext class:

@Test
public void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().build();

    HttpGet request = new HttpGet("http://www.github.com");

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
    response = instance.execute(request, localContext);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

4. Set the Cookie on the Low Level Request

A low level alternative of setting the cookie on the HTTP Request would be setting it as a raw Header:

@Test
public void whenSettingCookiesOnARequest_thenCorrect() 
  throws ClientProtocolException, IOException {
    instance = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("http://www.github.com");
    request.setHeader("Cookie", "JSESSIONID=1234");

    response = instance.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

This is of course much more error-prone than working with the built in cookie support. For example, notice that we’re no longer setting the domain in this case – which is not correct.

5. Conclusion

This article illustrated how to work with the HttpClient to send a custom, user controlled Cookie.

Note that this is not the same as letting the HttpClient deal with the cookies set by a server. Instead, it’s controlling the client side manually at a low level.

The implementation of all these examples and code snippets can be found in my github project.

Related posts:

REST Web service: Upload và Download file với Jersey 2.x
Map Serialization and Deserialization with Jackson
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Spring WebClient and OAuth2 Support
Tính kế thừa (Inheritance) trong java
Spring 5 Testing with @EnabledIf Annotation
So sánh ArrayList và LinkedList trong Java
Java Program to Create the Prufer Code for a Tree
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java Program to Implement Fenwick Tree
Hướng dẫn Java Design Pattern – Composite
Spring Boot - Cloud Configuration Server
Java Program to Implement Tarjan Algorithm
Java Program to Implement ConcurrentSkipListMap API
Convert a Map to an Array, List or Set in Java
Java Program to Find Number of Articulation points in a Graph
So sánh ArrayList và Vector trong Java
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Java Program to Implement Doubly Linked List
Simplify the DAO with Spring and Java Generics
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java Program to Implement Disjoint Sets
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Hướng dẫn Java Design Pattern – Dependency Injection
Introduction to Spring Data MongoDB
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Implement Pairing Heap
Spring Boot - Thymeleaf
Guava Collections Cookbook
Hướng dẫn Java Design Pattern – Facade