Frizz
Frizz

Reputation: 2544

Overwrite HTTP Header in CXF (JAX-RS)

I would like to change the value of the HTTP Header "Connection" before sending a reply from the Server to the Client.

My Use Case: I have a JAX-RS Web Service that sits behind a Load Balancer. The Web Service Client sends requests with "Connection: Keep-Alive". Result: The connection is kept open, the Load Balancer does not balance :-)

So I would like my Web Service to reply every few hundred requests with a "Connection: close" to force the Client to open a new connection.

How can I do this with CXF?

Upvotes: 0

Views: 961

Answers (1)

suenda
suenda

Reputation: 693

You can use a ContainerResponseFilter to add your desired header to the response sent.

An example:

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

@Provider
public class ResponseFilter implements ContainerResponseFilter {

    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        MultivaluedMap<String, Object> headers = responseContext.getHeaders();
        headers.putSingle("Connection", "close");
    }

}

Declare this class as a Provider in your javax.ws.rs.core.Application.

Upvotes: 1

Related Questions