Java REST服务返回错误的内容类型和解组
我使用的是RESTEasy,更具体地说,是他们框架的客户端 我正在调用第三方web服务,该服务将返回一些JSON代码 但是,出于一些好的原因,他们的响应中的内容类型是“text/javascript” 我如何告诉RESTEasy它应该为“text/javascript”内容类型使用JSON提供程序(解组目的) 可能吗 我的代码:Java REST服务返回错误的内容类型和解组,java,rest,resteasy,Java,Rest,Resteasy,我使用的是RESTEasy,更具体地说,是他们框架的客户端 我正在调用第三方web服务,该服务将返回一些JSON代码 但是,出于一些好的原因,他们的响应中的内容类型是“text/javascript” 我如何告诉RESTEasy它应该为“text/javascript”内容类型使用JSON提供程序(解组目的) 可能吗 我的代码: public interface XClient { @GET @Produces("application/json") @Path("/api/x.json"
public interface XClient {
@GET
@Produces("application/json")
@Path("/api/x.json")
public Movie getMovieInformation(
@QueryParam("q") String title);
}
解决方案可能是什么样的:
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);
}
我的时间不多了,所以这帮我搞定了。我已将服务器的响应标记为字符串,并已使用Jackson手动处理解组:
public interface XClient {
@GET
@Path("/api/x.json")
@Produces(MediaType.APPLICATION_JSON)
public String getMovieInformation(
@QueryParam("q") String title,
}
在我的休息电话中:
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();
}
如果这不是更好的解决方案,请告知。但这似乎是可行的。我通过使用一个拦截器替换传入的内容类型来解决问题,如下所示:
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;
}
}
但这会影响所有传入的请求?是的,所有的响应,正如我们在这里讨论的REST客户机一样。如果您正在与之交谈的服务返回JSON作为
text/javascript
,那么这通常也是您想要的。默认情况下,客户端无法处理此内容类型。