Brad Parks
Brad Parks

Reputation: 71961

Java: How to remove a header from a response?

I've got a Response that's created by a ResponseBuilder, and want to remove a header from it if it's already there, to ensure I don't get multiple values set for the same header (content-disposition).

How can I do this?

Upvotes: 3

Views: 4613

Answers (1)

Brad Parks
Brad Parks

Reputation: 71961

For my use case, I found that I could remove any existing header by setting the header to null first, then setting the new value.

e.g.

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("response_test")
@GET
public Response response(){

    // Pretend we've got a response builder that was created by 
    // some code we don't control
    ResponseBuilder builder = Response.status(200);
    builder.entity("Test Me");
    builder.header("content-disposition", "attachment; filename=a.txt");

    // Now remove any "content-disposition" header that's there
    // and replace it with our updated header.
    builder.header("content-disposition", null);
    builder.header("content-disposition", "attachment; filename=b.txt");
    Response response = builder.build();
    return response;
}

Upvotes: 3

Related Questions