Springboot 3.2.0自定义RestTemplate不发送Content-Length

wpx232ag  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(133)

我有一个springboot 3.1.5应用程序,我试图升级到Springboot 3.2.0。这个应用程序使用自定义RestTemplate对另一个服务器进行REST调用。自定义RestTemplate(基于Apache HttpClient 5.2.3)被构造为忽略SSL证书验证。
被调用的服务器返回:411 Length Required。当将debug添加到springboot 3.2.0应用程序时,似乎没有使用springboot 3.2.0设置“Content-length”header。当运行Spring 3.1.5时,即使使用相同版本的HttpClient,也会设置“Content-Length”。
如果我发送一个空字符串(“”),当没有主体的post请求,这是工作的。同样,当我手动序列化对象到字符串,它的工作。

0yg35tkg

0yg35tkg1#

发行说明解释了为什么没有Content-Length。
下面是我的Springboot 3.2.0的RestTemplate,它设置了Content-Length:

@Bean
@SneakyThrows
public RestTemplate restTemplate() {

    SSLContext sslContext = SSLContextBuilder.create()
            .loadTrustMaterial((X509Certificate[] certificateChain, String authType) -> true)  // <--- accepts each certificate
            .build();

    Registry<ConnectionSocketFactory> socketRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(URIScheme.HTTPS.getId(), new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
            .register(URIScheme.HTTP.getId(), new PlainConnectionSocketFactory())
            .build();

    HttpClient httpClient = HttpClientBuilder.create()
            .setConnectionManager(new PoolingHttpClientConnectionManager(socketRegistry))
            .setConnectionManagerShared(true)
            .build();

    // Use BufferingClientHttpRequestFactory to ensure Content-Length is added to the request.
    // See https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-6.x#web-applications
    // at the end.
    ClientHttpRequestFactory requestFactory = new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));

    return new RestTemplate(requestFactory);

}

字符串
添加BufferingClientHttpRequestFactory允许Content-Length作为头文件添加。

相关问题