开发者

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 开发者_如何学JAVAservice 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.


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);
    }
});


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;
    }
}


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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜