sksamuel
sksamuel

Reputation: 16387

How to override response header in jersey client

I have a jersey client that I am trying to unmarshall a response entity with. The problem is the remote web service sends back application/octet-stream as the content type so Jersey does not know how to unmarshall it (I have similar errors with text/html coming back for XML and such). I cannot change the web service.

What I want to do is override the content-type and change it to application/json so jersey will know which marshaller to use.

I cannot register application/octet-stream with the json marshaller as for a given content type I actually might be getting back all kinds of oddities.

Upvotes: 2

Views: 5214

Answers (3)

CupawnTae
CupawnTae

Reputation: 14600

Under Java 8 and Jersey 2 you can do it with a lambda:

client.register((ClientResponseFilter) (requestContext, responseContext) ->
                responseContext.getHeaders().putSingle("Content-Type", "application/json"));

Upvotes: 1

laz
laz

Reputation: 28648

I'm not well-versed in the Jersey client API, but can you use a ClientFilter to do this? Perhaps you could add a property to the request via ClientRequest.getProperties().put(String, Object) that tells the ClientFilter what Content-Type to override the response with. If the ClientFilter finds the override property, it uses it, otherwise it does not alter the response. I'm not sure if the ClientFilter is invoked prior to any unmarshalling though. Hopefully it is!

Edit (Have you tried something like this):

public class ContentTypeClientFilter implements ClientFilter {
    @Override
    public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
        final ClientResponse response = getNext().handle(request);

        // check for overridden ContentType set by other code
        final String overriddenContentType = request.getProperties().get("overridden.content.type");
        if (overriddenContentType != null) {
            response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, overriddenContentType);
        }
        return response;
    }
}

Upvotes: 1

Martin Matula
Martin Matula

Reputation: 7989

As laz pointed out, ClientFilter is the way to go:

client.addFilter(new ClientFilter() {
    @Override
    public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
        request.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "application/json");
        return getNext().handle(request);
    }
});

Upvotes: 6

Related Questions