How to handle the wrong type of JSON content from web services using the standard JAX-RS client API?

I want to use the Rotten Tomatoes API to search for movies.

I have an equivalent fully working application that uses TMDB and not Rotten Tomatoes.

I am using the standard JAX-RS client provided by JBoss RESTEasy with the RESTEasy Jackson2 provider (I cannot publish my API key, of course):

public MovieSearchResults search(String query) { return client .target("http://api.rottentomatoes.com/api/public/v1.0/movies.json") .queryParam("apikey", API_KEY) .queryParam("q", query) .request(MediaType.APPLICATION_JSON) .get(MovieSearchResults.class); } 

The MovieSearchResults class is just an annotated JAXB class for JSON binding.

The immediate problem is that the Rotten Tomatoes API returns a response with the content type "text / javascript" for all of its JSON responses. They were reluctant to change their services, although this is clearly the wrong type of content that should be set when returning JSON, so right now that's what it is.

The exception that I get when I call the service:

 Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type text/javascript;charset=ISO-8859-1 and type class MovieSearchResults 

So the question is: is there an easy way to get / configure the standard JAX-RS client to recognize the return type of the content "text / javascript" as "application / json"?

These questions are similar, but the accepted answers seem to use the JBoss-specific API and I would like to do this only through the JAX-RS client API.

+6
source share
1 answer

The answer is to use the JAX-RS ClientResponseFilter.

Request modified to register filter:

 public MovieSearchResults search(String query) { return client .register(JsonContentTypeResponseFilter.class) .target("http://api.rottentomatoes.com/api/public/v1.0/movies.json") .queryParam("apikey", API_KEY) .queryParam("q", query) .request(MediaType.APPLICATION_JSON) .get(MovieSearchResults.class); } 

The filter itself simply replaces the content header:

 public class JsonContentTypeResponseFilter implements ClientResponseFilter { @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { List<String> contentType = new ArrayList<>(1); contentType.add(MediaType.APPLICATION_JSON); responseContext.getHeaders().put("Content-Type", contentType); } } 
+7
source

All Articles