Add proxy information and basic auth to resttemplate using httpClient

My development environment is behind the proxy server, so I need to set the proxy information to the rest of the template, which is good when I use the HttpComponentsClientHttpRequestFactory and set the proxy parameter to httpClient and set it in the template.

But now I have a recreation service that requires basic auth. And in order to set the basic credentials, I need to set them in httpClient in the break pattern. But I see that the getparams method in httpClient is deprived, 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 information that was installed during the initial loading of the application.

So is there a way I could extract the httpClient from the rest of the template and update it? Or is there any other way to handle this?

Thank.

+4
source share
2 answers

Configure httpClientas 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

+4
source

The above solution did not work for me, I am working on it and finally will make it work with minor changes.

RestTemplate restTemplate = new RestTemplate();
    HttpHost proxy =null;
    RequestConfig config=null;
    String credentials = this.env.getProperty("uname") + ":" + this.env.getProperty("pwd");
    String encodedAuthorization = Base64.getEncoder().encodeToString(credentials.getBytes());

    Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuthorization);
    List<Header> headers = new ArrayList<>();
    headers.add(header);

    if(Boolean.valueOf(env.getProperty("proxyFlag"))){
        proxy = new HttpHost(this.env.getProperty("proxyHost"), Integer.parseInt(env.getProperty("proxyPort")), "http");
        config= RequestConfig.custom().setProxy(proxy).build();
    }else{
        config= RequestConfig.custom().build();
    }


    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config)
            .setDefaultHeaders(headers).build();

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate.setRequestFactory(factory);

    return restTemplate;
0
source