How to override response header in jersey client

后端 未结 3 1807
盖世英雄少女心
盖世英雄少女心 2020-12-12 02:52

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 s

相关标签:
3条回答
  • 2020-12-12 03:10

    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);
        }
    });
    
    0 讨论(0)
  • 2020-12-12 03:11

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-12 03:11

    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 讨论(0)
提交回复
热议问题