带有xml和json的Spring Boot只返回xml

时间:2017-08-17 06:58:01

标签: json xml spring jackson

我先感谢你的帮助!

我在Spring启动应用程序中有一种奇怪的行为。让我为你解释一下:

我正在使用一些不错的rest-json服务包装一些遗留的Web服务(自定义xml消息)(通过spring-mvc和spring boot以及使用jackson来序列化东西)

为了与遗留系统进行通信,我创建了一个自定义的XmlMapper,序列化器和反序列化器。

最后,我创建了一个httpclientconfig,以便定义一些http连接属性......

但是在启动应用程序并尝试访问任何端点(例如执行器)之后,应用程序只返回xml。事件招摇终点返回xml(是什么让swagger-ui疯狂。

这些是一些类:

    @Configuration
    public class HttpClientConfig {
        private static final Logger logger = LoggerFactory.getLogger(HttpClientConfig.class);
        @Value(value = "${app.http.client.max_total_connections}")
        public String MAX_TOTAL_CONNECTIONS;

        @Value(value = "${app.http.client.max_connections_per_route}")
        public String MAX_CONNECTIONS_PER_ROUTE;

        @Value(value = "${app.http.client.connection_timeout_milliseconds}")
        public String CONNECTION_TIMEOUT_MILLISECONDS;

        @Bean
        public ClientHttpRequestFactory httpRequestFactory() {
            return new HttpComponentsClientHttpRequestFactory(httpClient());
        }
        @Autowired 
        private XmlMapper xmlMapper;
        @Bean
        public RestTemplate restTemplate() {
            RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
            List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();

            for (HttpMessageConverter<?> converter : converters) {
                if (converter instanceof MappingJackson2HttpMessageConverter) {
                    MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
                    jsonConverter.setObjectMapper(new ObjectMapper());
                }
                if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
                    MappingJackson2XmlHttpMessageConverter jsonConverter = (MappingJackson2XmlHttpMessageConverter) converter;              
                    jsonConverter.setObjectMapper(xmlMapper);
                }
            }

            logger.debug("restTemplate object created====================================");
            return restTemplate;
        }

        @Bean
        public HttpClient httpClient() {
            HttpClient httpClient = null;
            try {
                HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

                // disable SSL check
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {
                        return true;
                    }
                }).build();
                httpClientBuilder.setSSLContext(sslContext);
                // don't check Hostnames
                HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
                SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslSocketFactory).build();

                PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
                connMgr.setMaxTotal(Integer.parseInt(MAX_TOTAL_CONNECTIONS));
                connMgr.setDefaultMaxPerRoute(Integer.parseInt(MAX_CONNECTIONS_PER_ROUTE));
                RequestConfig config = RequestConfig.custom()
                        .setConnectTimeout(Integer.parseInt(CONNECTION_TIMEOUT_MILLISECONDS)).build();

                httpClientBuilder.setDefaultRequestConfig(config);
                httpClientBuilder.setConnectionManager(connMgr);

                // to avoid nohttpresponse
                httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {

                    @Override
                    public boolean retryRequest(IOException exception, int executionCount,
                            org.apache.http.protocol.HttpContext context) {
                        // TODO Auto-generated method stub
                        return true;
                    }
                });
                httpClient = httpClientBuilder.build();
            } catch (Exception e) {
                logger.error("Excption creating HttpClient: ", e);
            }
            return httpClient;
        }
    }

和xml映射器

    @Configuration
    public class XmlMapperConfig{

        @Bean
        public XmlMapper getXmlMapper() {
            XmlMapper mapper=new XmlMapper();       
            SimpleModule module = new SimpleModule();       
            module.addSerializer(CafRequestObject.class, new CafRequestObjectSerializer());
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.registerModule(module);      
            mapper.findAndRegisterModules();
            CafXmlSerializationProvider cafXmlProvider=new CafXmlSerializationProvider(new XmlRootNameLookup());        

            mapper.setSerializerProvider(cafXmlProvider);
            return mapper;
        }


    }

我调用findAndregisterModules,因为我也在开发一些库,为服务提供额外的序列化器(模块化的东西)

我完全迷失了。任何帮助将不胜感激......

问候!

1 个答案:

答案 0 :(得分:0)

我已经解决了它扩展WebMvcConfigurerAdapter:

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {


        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.defaultContentType(MediaType.APPLICATION_JSON);
        }
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
                .addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
            registry
                .addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

再次感谢!