如何禁用弹簧执行器的内容协商?

时间:2019-11-22 17:30:00

标签: java spring-boot spring-boot-actuator content-negotiation

当执行器端点/info/health被调用时,我想禁用内容协商

这是我的配置文件

@Configuration
public class InterceptorAppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML);
    }
}

当我curl http://localhost:8081/health

我收到:

DefaultHandlerExceptionResolver Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

但是,当我在Chrome中启动相同的网址时,我会收到有效的回复。

在我的情况下,应在不使用标头的情况下调用执行器(没有-H'Accept:...')

2 个答案:

答案 0 :(得分:1)

不幸的是,我只能提供次优的解决方案。

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML)
            .defaultContentTypeStrategy((webRequest) -> {
                final String servletPath = ((HttpServletRequest) webRequest.getNativeRequest()).getServletPath();
                final MediaType defaultContentType = Arrays.asList("/info", "/health").contains(servletPath)
                        ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML;
                return Collections.singletonList(defaultContentType);
            });
}

如果返回/info/health端点称为application/json的情况。对于所有其他请求,都使用默认的application/xml

答案 1 :(得分:0)

添加defaultContentTypeStrategy并处理null或通配符接受。

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.defaultContentType(MediaType.APPLICATION_XML)
    .mediaType("json", MediaType.APPLICATION_JSON)
    .mediaType("xml", MediaType.APPLICATION_XML);

    configurer.defaultContentTypeStrategy(new ContentNegotiationStrategy() {
        @Override
        public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {
            // If you want handle different cases by getting header with webRequest.getHeader("accept")
            return Arrays.asList(MediaType.APPLICATION_JSON);
        }
    });       
}