Search code examples
javaspringspring-bootresttemplatespring-resttemplate

SpringBoot upgrade RestTemplateBuilder from 1.5.14 to 2.1.5


I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .requestFactory(new MyHttpComponentFactoryBuilder()
                        .build())
                .build();

After updating to RestTemplateBuilder 2.1.5 I have this piece of code:

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(connectTimeout))
                .setReadTimeout(Duration.ofMillis(readTimeout))
                .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
                .build();

but when running the code I have a InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) , but debugging new MyHttpComponentFactoryBuilder().build().getClass() is not null

I also tried with the solution proposed:

... 
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {

            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

    }

but I have also a InvocationTargetException / NullPointerException


Solution

  • The below code shows how you need to create the template for simple cases.

    RestTemplate tmpl = new RestTemplateBuilder().setConnectTimeout(Duration.ofMillis(200))
                                                 .setReadTimeout(Duration.ofMillis(100))
                                                 .requestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory.class)
                                                 .build();
    

    It would be better for you to provide the source code of MyHttpComponentFactoryBuilder class. But my suggestion is that to create a class MyHttpComponentFactory which extends SimpleClientHttpRequestFactory class migrate your codes from MyHttpComponentFactoryBuilder to it.