How to override response header in jersey client

I have a jersey client with which I am trying to disconnect a response object. The problem is that the remote web service sends the application / octet stream back as the content type, so Jersey doesn't know how to deploy it (I have similar errors with text / html returning for XML, etc.) . I cannot change the web service.

What I want to do is redefine the content type and change it to application / json so that the jersey knows which marshaller to use.

I cannot register an application / octet stream with a json marshaller, since for a certain type of content I really could return all kinds of oddities.

+2
json rest jersey
Jul 18 2018-11-11T00:
source share
3 answers

As Laz noted, 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); } }); 
+5
Sep 18 '11 at 9:26 a.m.
source share

I am not good at the Jersey client API, but can you use ClientFilter to do this? Perhaps you could add a property to the request through ClientRequest.getProperties().put(String, Object) , which tells ClientFilter that the Content-Type to cancel the response. If the ClientFilter finds an override property, it uses it, otherwise it will not modify the response. I am not sure if ClientFilter is called before any unmarshalling. I hope so!

Edit (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; } } 
+1
Jul 18 '11 at 18:07
source share

In Java 8 and Jersey 2, you can do this with lambda:

 client.register((ClientResponseFilter) (requestContext, responseContext) -> responseContext.getHeaders().putSingle("Content-Type", "application/json")); 
+1
Sep 17 '15 at 17:50
source share



All Articles