Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The appropriate method to proxy TestRestTemplate connections is to configure a bean of type RestTemplateCustomizer with a custom RestTemplate that has a ClientHttpRequestFactory configured to use a Proxy. Then register that bean with the TestRestTemplateBuilder. Here's an example configuration:

@Configuration
public class TestRestTemplateConfig {

    @Value("${proxy.host}")
    private String proxyHost;

    @Value("${proxy.port}")
    private int proxyPort;

    @Bean
    public RestTemplateCustomizer restTemplateCustomizer() {
        return restTemplate -> {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // Add proxy settings
            httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)));

            HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpComponentsClientHttpRequestFactory.setHttpClient(httpClientBuilder.build());
            restTemplate.setRequestFactory(httpComponentsClientHttpRequestFactory);
        };
    }

    @Bean
    public TestRestTemplateBuilder testRestTemplateBuilder(RestTemplateBuilder restTemplateBuilder, RestTemplateCustomizer restTemplateCustomizer) {
        return new TestRestTemplateBuilder(restTemplateBuilder).apply(restTemplateCustomizer);
    }
}

In this example configuration, the RestTemplateCustomizer bean configures a HttpClientBuilder with proxy settings by setting a new DefaultProxyRoutePlanner on the builder. Then a HttpComponentsClientHttpRequestFactory is created with the HttpClient from the builder and is set as the RequestFactory for the RestTemplate.

Finally, the TestRestTemplateBuilder bean is created by passing in a RestTemplateBuilder and the RestTemplateCustomizer bean. The RestTemplateCustomizer will be applied to any RestTemplate created by the TestRestTemplateBuilder, allowing for proxy connections to be established.