RESTEasy client

First let’s create a RESTEasy client

BooksService client = new ResteasyClientBuilder()
			.build()
			.target(url)
			.proxy(BooksService.class);

ClientRequestFilter

In order to add cookies to RESTEasy client requests we need to implement the ClientRequestFilter interface.

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Cookie;
import java.util.ArrayList;
import java.util.List;

public class AddCookieClientFilter implements ClientRequestFilter {

    private Cookie cookie;

    public AddCookieClientFilter(Cookie cookie) {
        super();
        this.cookie = cookie;
    }

    @Override
    public void filter(ClientRequestContext clientRequestContext) {
        List<Object> cookies = new ArrayList<>();
        cookies.add(this.cookie);
        clientRequestContext.getCookies().entrySet().stream().forEach(item -> cookies.add(item.getValue()));
        clientRequestContext.getHeaders().put("Cookie", cookies);
    }
}

Register RequestFilter

Now we need to register the filter that we created.

register(new AddCookieClientFilter(cookie));

Finally let’s update the REASTEasy client

BooksService client = new ResteasyClientBuilder()
			.build()
			.register(new AddCookieClientFilter(new Cookie(cookieName, cookieValue)))
			.target(url)
			.proxy(BooksService.class);

Now all requests will include the Cookie header with the cookie that we just added.