Spring RestTemplate Post Issue

时间:2016-10-26 16:57:25

标签: spring resttemplate

尝试使用Spring Rest Template发布时,我面临以下问题,

以下是我的代码,

配置

            @Bean
            @Qualifier("restService")
            public RestTemplate createRestTemplate(
                    @Value("${profileRetreival.client.readTimeoutMillis}") Integer maxReadTimeOut,
                    @Value("${profileRetreival.client.connectionTimeoutMillis}") Integer maxTimeOut) {

                HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                        httpClient());
                clientHttpRequestFactory.setConnectTimeout(maxTimeOut);
                clientHttpRequestFactory.setReadTimeout(maxReadTimeOut);

                RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

                restTemplate.setErrorHandler(new RestResponseErrorHandler());
                //restTemplate.setMessageConverters(createMessageConverters());

                return restTemplate;
            }

Restemplate类

public HttpHeaders prepareheaders() {
                    HttpHeaders headers = new HttpHeaders();
                    headers.add(CONSUMER, "*****");
                    headers.add(CLIENT, "*******");
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                    return headers;
            }



        HttpEntity<String> request= new HttpEntity<>( req.toString(), prepareheaders() );

        ResponseEntity<FooData> response = restClient.exchange(url, HttpMethod.POST, request, FooData.class);

        System.err.println(response.getBody()

上面的代码工作正常。 但是如果我将MappingJackson2HttpMessageConverter添加到配置步骤,则会从服务中收到错误

List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
        jsonMessageConverter.setObjectMapper(getObjectMapper());
        messageConverters.add(jsonMessageConverter);

        restTemplate.setMessageConverters(createMessageConverters());

并发布如下,

 FooData response = restClient.postForObject(url, request, FooData.class);

            System.err.println(response)

这会导致500状态代码,内部服务器错误

如果我做错了或正确的方法,请有人指出我。杰克逊转换器是一个不需要的补充,因为Spring会这样做吗

0 个答案:

没有答案