yogiginger yogiginger - 1 year ago 1123
Java Question

Spring RestTemplate and Proxy Auth

I'm trying to do REST calls with Spring. As I understand, the right way to go is using

(?). Problem is, I'm behind a proxy.

This is my code right now:

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
InetSocketAddress address = new InetSocketAddress(host, 3128);
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);

RestTemplate restTemplate = new RestTemplate();

Seems to work, but I need to authenticate at the proxy, but how is this done? The
type as well as the
type don't seem to handle credentials. Without credentials, I'm getting just 407...

Answer Source

After quite a few different options I settled on The below code due to the ability to set the proxy for the RestTemplate at creation so I could refactor it into a separate method. Just to note it also has an additional dependency so keep that in mind.

    private RestTemplate createRestTemplate() throws Exception {
        final String username = "myusername";
        final String password = "myPass";
        final String proxyUrl = "proxy.nyc.bigtower.com";
        final int port = 8080;

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
                new AuthScope(proxyUrl, port), 
                new UsernamePasswordCredentials(username, password));

        HttpHost myProxy = new HttpHost(proxyUrl, port);
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();


        HttpClient httpClient = clientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

        return new RestTemplate(factory);

//Dependencies I used.