Search code examples
springproxybasic-authenticationresttemplate

Add proxy information and basic auth to the resttemplate using httpClient


My development environment is behind a proxy so i need to set the proxy information to the rest template, that's all good when i use a HttpComponentsClientHttpRequestFactory and set the proxy setting in the httpClient and set it in the template.

But now i have a rest service that needs basic auth. And to set the basic auth credentials, i need to set them in the httpClient on the rest template. But i see that the getparams method in the httpClient is depricated, so i can't just update the existing client in the template, and if i create a new httpclient object, i will overwrite the proxy info that were set during the application bootstrapping.

So is there some way that i could extract the httpClient from the rest template and update it? Or is there any other way to tackle this?

Thanks.


Solution

  • Configure the httpClient as follows:

    HttpHost target = new HttpHost("hostname", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    
    HttpHost proxy = new HttpHost("proxy", 12345);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setProxy(proxy)
            .setDefaultCredentialsProvider(credsProvider).build();
    
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpclient);
    
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    

    See also HttpClient Examples