Spring RestTemplate getForObject在重用多个请求后包含重复的标头

时间:2017-09-23 10:59:49

标签: java spring spring-boot

我用

@Autowired
private RestTemplate restTemplate;

在我的每一次使用中。我在我的Application类中初始化了RestTemplate:

@Bean
public RestTemplate restTemplate() {

    SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
    httpRequestFactory.setConnectTimeout(30 * 1000);
    httpRequestFactory.setReadTimeout(30 * 1000);

    return new RestTemplate(httpRequestFactory);
}

请告诉我这个问题的原因。无论如何,如果我出错了,也要纠正我。

3 个答案:

答案 0 :(得分:0)

最后,我找到了避免重复标题的解决方案:

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

答案 1 :(得分:0)

在我的情况下,原因是在使用此bean的每个请求的自动连接的resttemplate中注册了消息转换器,因此破坏了整个应用程序的resttemplate bean。 由于每个消息转换器都提供了自己的“接受”功能,因此每个请求都重复了该消息(此错误已在Spring 5.x中修复,现在仅向服务器发送了唯一的接受值)

答案 2 :(得分:-1)

尝试使用@Component更改@Bean并让我知道它是否有效