小编典典

Spring Boot单例RestTemplate接受标头不断被附加到

spring-boot

我正在使用Spring Boot(1.3.0.RELEASE)。我需要使用RestTemplate调用许多不同的REST
Web服务。显然,我不想每次调用都创建一个RestTemplate的新实例,因此我为RestTemplate的一个实例创建了一个配置,如下所示:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

上面的代码被自动装配成许多类,需要调用外部REST服务…有很多!有些要获取,有些要执行POST

USAGE ------------------------
ResponseEntity<String> response =
getRestTemplate().exchange(getUri(), HttpMethod.GET, request, String.class);

USAGE------------------------ 
getRestTemplate().getMessageConverters().add(new StringHttpMessageConverter());            
String response = getRestTemplate().getForObject(getUri(), String.class, toc);
------------------------

因此,我注意到“接受Http标头”存在问题。它似乎保持增长,即它被附加。我没有在代码中设置任何Accept标头!这就是我在日志中看到的。

     [http-nio-9080-exec-1] o.s.web.client.RestTemplate              
: Setting request Accept header to [text/plain, application/json,
 application/*+json, text/plain, text/plain, text/plain, text/plain, 
text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, text/plain, */*, */*, */*, */*, */*, */*, */*, */*, 
*/*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, 
*/*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, 
*/*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, */*, 
*/*, */*, */*, */*, */*, */*]

这可能会增长,最终会得到400(错误请求)

org.springframework.web.client.HttpClientErrorException: 400 Bad Request
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
        at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
        at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:264) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]

那么将RestTemplate声明为单例bean实例的问题吗?即,由于可以调用许多Web服务,因此使用了相同的RestTemplate,因此Accept
Header保持增长吗?

有人可以帮我解决这个问题吗?


阅读 1463

收藏
2020-05-30

共1个答案

小编典典

因为您的@Bean方法返回一个单例,所以您RestTemplate在调用该方法时始终会得到相同的实例(每次不会获得新的实例)。

在用法部分,似乎您StringHttpMessageConverter每次使用此REST模板时都会添加一次。一遍又一遍地添加此消息转换器可能是它添加新的Accept标头的原因。

将您的消息转换器配置移到您的@Bean方法中,该问题将消失。

2020-05-30