Last active
February 18, 2025 17:48
-
-
Save davidtimmerman/86ae3822075aad16edc0 to your computer and use it in GitHub Desktop.
Spring RestTemplate with proxy settings
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.logging.log4j.LogManager; | |
import org.apache.logging.log4j.Logger; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.http.client.SimpleClientHttpRequestFactory; | |
import org.springframework.stereotype.Component; | |
import org.springframework.web.client.RestTemplate; | |
import javax.annotation.PostConstruct; | |
import java.net.InetSocketAddress; | |
import java.net.Proxy; | |
@Component | |
public final class RestProxyTemplate { | |
final Logger logger = LogManager.getLogger(RestProxyTemplate.class); | |
@Autowired | |
RestTemplate restTemplate; | |
@Value("${proxy.host}") | |
String host; | |
@Value("${proxy.port}") | |
String port; | |
@PostConstruct | |
public void init(){ | |
int portNr = -1; | |
try { | |
portNr = Integer.parseInt(port); | |
} catch (NumberFormatException e) { | |
logger.error("Unable to parse the proxy port number"); | |
} | |
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); | |
InetSocketAddress address = new InetSocketAddress(host,portNr); | |
Proxy proxy = new Proxy(Proxy.Type.HTTP,address); | |
factory.setProxy(proxy); | |
restTemplate.setRequestFactory(factory); | |
} | |
public RestTemplate getRestTemplate() { | |
return restTemplate; | |
} | |
} |
what about socks proxy?
For socks:
Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! And the Spring-Bean configuration version is here: http://docs.spring.io/spring-integration/reference/html/http.html#http-proxy.