如何覆盖JAX-RS内容协商期间做出的决策?

jho*_*der 5 java rest jax-rs resteasy

我正在使用RESTEasy 2.2.1.GA作为我的JAX-RS实现来创建连接到第三方服务提供商的客户端.(如果重要的话,Education.com的REST API)

为了确保我没有错过重要的实现细节,这里有代码示例:

服务接口

@Path("/")
public interface SchoolSearch {

@GET
@Produces({MediaType.APPLICATION_XML})
Collection<SchoolType> getSchoolsByZipCode(@QueryParam("postalcode") int postalCode);
}
Run Code Online (Sandbox Code Playgroud)

打电话给班级

public class SimpleSchoolSearch {

public static final String SITE_URL = "http://api.education.com/service/service.php?f=schoolSearch&key=****&sn=sf&v=4";

SchoolSearch service = ProxyFactory.create(SchoolSearch.class, SITE_URL);

public Collection<SchoolType> getSchools() throws Exception {
    Collection<SchoolType> schools = new ArrayList<SchoolType>();
    Collection<SchoolType> response = service.getSchoolsByZipCode(35803);
    schools.addAll(response);
    return schools;

}
}
Run Code Online (Sandbox Code Playgroud)

在设置测试以进行此调用之后,我执行并看到抛出以下异常.

org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: Unable to find JAXBContext for media type: text/html;charset="UTF-8"
Run Code Online (Sandbox Code Playgroud)

从读取RESTEasy/JAX-RS文档,据我所知,当响应返回给客户端时,在解组数据之前,确定(内容协商??)关于使用哪种机制进行解组.(我想我们在这里谈论的是一个MessageBodyReader,但我不确定.)从查看响应的主体,我看到返回的是格式正确的XML,但是内容协商(通过HTTP头内容类型是确实是text/html; charset ="UTF-8")不允许JAXB解析文本.

我认为实现是正确的行为,并且它是错误的服务,但是,我不控制服务,但仍然想要使用它.

所以说:

我是否理解为什么会抛出异常?

我该如何解决?

是否有一个简单的一行注释可以强制JAXB解组数据,还是需要实现一个自定义的MessageBodyReader?(如果这甚至是正确的类来实现).

谢谢!

跟进:

我只是想对艾登的答案发表一些变化.我使用他的代码和Resteasy ClientExecutionInterceptor文档中提供的信息创建了一个ClientExecutionInterceptor .我的最后一堂课看起来像

@Provider
@ClientInterceptor
public class SimpleInterceptor implements ClientExecutionInterceptor {

@Override
  public ClientResponse execute(ClientExecutionContext ctx) throws Exception {
      final ClientResponse response = ctx.proceed();
      response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
      return response;
  }
}
Run Code Online (Sandbox Code Playgroud)

最大的区别是添加了@Provider和@ClientExecutionInterceptor注释.这应该确保拦截器正确注册.

另外,为了完整性,我为我的测试注册了Interceptor略有不同.我用了:

        providerFactory.registerProvider(SimpleInterceptor.class);
Run Code Online (Sandbox Code Playgroud)

eid*_*den 2

我确信这个问题有多种解决方案,但我只能想到一个。

尝试使用 ClientExecutionInterceptor 设置内容类型:

public class Interceptor implements ClientExecutionInterceptor {

    @Override
    public ClientResponse<?> execute(ClientExecutionContext ctx) throws Exception {
        final ClientResponse<?> response = ctx.proceed();

        response
            .getHeaders()
            .putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);

        return response;
    }

}

public void getSchools() throws Exception {
    ResteasyProviderFactory.getInstance()
        .getClientExecutionInterceptorRegistry()
        .register( new Interceptor() );

    SchoolSearch service =
            ProxyFactory.create(SchoolSearch.class, SITE_URL);
}
Run Code Online (Sandbox Code Playgroud)