Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter? Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter? java java

Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter?


@AHungerArtist's answer works for simple use cases, where you want all requests to use the same proxy. If you need some requests through restTemplate to use the proxy, and others to not, though, you may find this more useful. (Or if you just like doing it programmatically more than you like mucking with system properties!)

@Beanpublic RestTemplate restTemplate() {    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();    Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("my.host.com", 8080));    requestFactory.setProxy(proxy);    return new RestTemplate(requestFactory);}

You should be able to create a copy of the restTemplate bean that way, and another one the normal way, so you can send requests with and without the proxy.


Sadly, this was really easy.

Properties props = System.getProperties();props.put("http.proxyHost", "localhost");props.put("http.proxyPort", "9080");


Spring has a good documentation using a Customizer to determine different proxy

public class ProxyCustomizer implements RestTemplateCustomizer {    @Override    public void customize(RestTemplate restTemplate) {        final String proxyUrl = "proxy.example.com";        final int port = 3128;        HttpHost proxy = new HttpHost(proxyUrl, port);        HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {            @Override            protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context)                    throws HttpException {                if (target.getHostName().equals("gturnquist-quoters.cfapps.io")) {                    return super.determineProxy(target, request, context);                }                return null;            }        }).build();        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));    }}

and the call to apply the ProxyCustomizer is

@Beanpublic RestTemplate restTemplate(RestTemplateBuilder builder) {    return builder.additionalCustomizers(new ProxyCustomizer()).build();}