【问题标题】:REST Service returning wrong content-type and unmarshallREST 服务返回错误的内容类型并解组
【发布时间】:2012-03-25 09:09:07
【问题描述】:

我使用的是 RESTEasy,更具体地说,是他们框架的客户端。

我正在调用向我返回一些 JSON 代码的第三方 Web 服务。

但是,出于某些原因,他们响应中的内容类型是“text/javascript”。

我如何告诉 RESTEasy 它应该使用 JSON 提供程序(解编组目的)作为“text/javascript”内容类型?

这可能吗?

我的代码:

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);
}

【问题讨论】:

    标签: java rest resteasy


    【解决方案1】:

    我通过使用替换传入内容类型的拦截器来解决,如下所示:

    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,这通常也是您想要的。无论如何,客户端默认无法处理此内容类型。
    【解决方案2】:

    我的时间不多了,所以这对我有用。我已经将来自服务器的响应标记为字符串,并且我已经手动处理了杰克逊的解组:

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

    并且,在我的 REST 调用中:

    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();
    }
    

    如果这不是更好的解决方案,请告知。但这似乎行得通。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2014-07-11
      • 2018-09-30
      • 1970-01-01
      相关资源
      最近更新 更多