Skip to content

Instantly share code, notes, and snippets.

@jurigis
Forked from davidtimmerman/RestProxyTemplate.java
Last active December 2, 2022 16:05
Show Gist options
  • Save jurigis/b60ff668aad900f51aaf837eaa060bf0 to your computer and use it in GitHub Desktop.
Save jurigis/b60ff668aad900f51aaf837eaa060bf0 to your computer and use it in GitHub Desktop.
Spring RestTemplate with proxy settings and proxy authentication
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
@Component
public class RestProxyTemplate {
private static final Logger LOGGER = LoggerFactory.getLogger(RestProxyTemplate.class);
private RestTemplate restTemplate;
@Value("${proxy.host}")
private String proxyHost;
@Value("${proxy.port}")
private String proxyPort;
@Value("${proxy.user}")
private String proxyUser;
@Value("${proxy.password}")
private String proxyPassword;
@PostConstruct
public void init() {
this.restTemplate = new RestTemplate();
final int proxyPortNum = Integer.parseInt(proxyPort);
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPortNum), new UsernamePasswordCredentials(proxyUser, proxyPassword));
final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.useSystemProperties();
clientBuilder.setProxy(new HttpHost(proxyHost, proxyPortNum));
clientBuilder.setDefaultCredentialsProvider(credsProvider);
clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
final CloseableHttpClient client = clientBuilder.build();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(client);
restTemplate.setRequestFactory(factory);
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
}
@stefanlechner
Copy link

Why don't you declare proxyPort as Integer ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment