REST Service returning wrong content-type and unma

2019-07-20 22:27发布

问题:

I'm using RESTEasy and more specifically, the client side of their framework.

I'm calling a third part web service that's returning me some JSON code.

But, for some good reasons, the content-type in their response is "text/javascript".

How can I tell RESTEasy that it should be using a JSON provider (unmarshalling purposes) for a "text/javascript" content-type ?

Is that possible ?

My code :

public interface XClient {  

@GET
@Produces("application/json")
@Path("/api/x.json")
public Movie getMovieInformation(
        @QueryParam("q") String title);
}

What an solution could be like :

public interface XClient {  

@GET
@Produces("text/javascript")
// Tell somehow to use json provider despite the produces annotation
@Path("/api/x.json")
public Movie getMovieInformation(
        @QueryParam("q") String title);
}

回答1:

I solved by using an interceptor that replaces incoming content type, like this:

this.requestFactory.getSuffixInterceptors().registerInterceptor(
    new MediaTypeInterceptor());


static class MediaTypeInterceptor implements ClientExecutionInterceptor {

    @Override
    public ClientResponse execute(ClientExecutionContext ctx) throws Exception {
        ClientResponse response = ctx.proceed();
        String contentType = (String) response.getHeaders().getFirst("Content-Type");
        if (contentType.startsWith("text/javascript")) {
            response.getHeaders().putSingle("Content-Type", "application/json");
        }
        return response;
    }

}


回答2:

I'm running out of time, so this did the trick for me. I've marked the response from the server as String, and I've manually handle the unmarshall with Jackson :

public interface XClient {  

@GET
@Path("/api/x.json")
@Produces(MediaType.APPLICATION_JSON)
public String getMovieInformation(
        @QueryParam("q") String title,

}

and, in my REST call :

MovieRESTAPIClient client = ProxyFactory.create(XClient.class,"http://api.xxx.com");
String json_string = client.getMovieInformation("taken");

ObjectMapper om = new ObjectMapper();
Movie movie = null;
try {
    movie = om.readValue(json_string, Movie.class);
} catch (JsonParseException e) {
myLogger.severe(e.toString());
e.printStackTrace();
} catch (JsonMappingException e) {
myLogger.severe(e.toString());
    e.printStackTrace();
} catch (IOException e) {
    myLogger.severe(e.toString());
    e.printStackTrace();
}

Please advise if this is not the better solution. But this seems to work.