Forked from davidtimmerman/RestProxyTemplate.java
Last active
November 7, 2024 18:45
-
-
Save jurigis/b60ff668aad900f51aaf837eaa060bf0 to your computer and use it in GitHub Desktop.
Spring RestTemplate with proxy settings and proxy authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why don't you declare proxyPort as Integer ?