Jersey Client: How to Set Cookie in Request?

Lokesh Gupta

In this example, we will learn to set cookies into HTTP requests invoked by the Jersey client. This example makes use of Invocation.Builder for setting cookies into outgoing REST calls.

1. Syntax

The following is the syntax to set a cookie in a Jersey client request using the Cookie class provided by Jersey.

// Create a cookie
Cookie cookie = new Cookie("cookieName", "cookieValue");

// Add the cookie to the request
Invocation.Builder invocationBuilder = target.request();
invocationBuilder.cookie(cookie);

// Perform the HTTP request
Response response = invocationBuilder.get(); // or post(), put(), etc.

    2. Set Cookie Example

    To set a cookie in a REST API request, first get the reference of Invocation.Builder from webTarget.request() method, and then use its methods.

    // Create a Jersey client instance
    Client client = ClientBuilder.newClient();
    
    // Create a WebTarget representing the resource endpoint
    WebTarget target = client.target("http://example.com/api/resource");
    
    // Create a cookie
    Cookie cookie = new Cookie("cookieName", "cookieValue");
    
    // Add the cookie to the request
    Invocation.Builder invocationBuilder = target.request();
    invocationBuilder.cookie(cookie);
    
    // Perform the HTTP GET request
    Response response = invocationBuilder.get();
    
    // Process the response
    if (response.getStatus() == 200) {
        // Handle successful response
        String responseBody = response.readEntity(String.class);
        System.out.println("Response: " + responseBody);
    } else {
        // Handle error response
        System.err.println("Error: " + response.getStatus());
    }
    
    // Close the client
    client.close();

    3. REST API

    I have written below REST API below for testing purposes. It accepts the cookie parameters and prints the cookie value in the console.

    @GET
      @Produces(MediaType.APPLICATION_JSON)
      public Response getAllItems(@CookieParam(value="cookieParam1") String cookieParam1,
                                  @CookieParam(value="cookieParam2") String cookieParam2) {
    
        System.out.println("cookieParam1 is :: " + cookieParam1);
        System.out.println("cookieParam2 is :: " + cookieParam2);
    
        List items = List.of(new Item(1L, "Item1"), new Item(2L, "Item2"));
    
        return Response.ok().entity(items).build();
      }

    4. Demo

    Now let’s call the above REST API using Jersey client code as suggested in the first heading.

    Client client = ClientBuilder.newClient( new ClientConfig());
    WebTarget webTarget = client.target("http://localhost:8080/").path("items");
    
    Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
    Response response = invocationBuilder
        .cookie("cookieParam1","cookieValue1")
        .cookie(new Cookie("cookieParam2", "cookieValue2"))
        .get();
    
    List items = response.readEntity(List.class);
    Assertions.assertEquals(200, response.getStatus());

    The program output:

    cookieParam1 is :: cookieValue1
    cookieParam2 is :: cookieValue2

    Happy Learning !!

    Source Code on Github

    Comments

    Subscribe
    Notify of
    guest
    1 Comment
    Most Voted
    Newest Oldest
    Inline Feedbacks
    View all comments

    About Us

    HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

    It also shares the best practices, algorithms & solutions and frequently asked interview questions.

    Our Blogs

    REST API Tutorial

    Dark Mode

    Dark Mode