Skip to content

Instantly share code, notes, and snippets.

@davidtimmerman
Last active February 13, 2024 08:33
Show Gist options
  • Save davidtimmerman/86ae3822075aad16edc0 to your computer and use it in GitHub Desktop.
Save davidtimmerman/86ae3822075aad16edc0 to your computer and use it in GitHub Desktop.
Spring RestTemplate with proxy settings
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;
}
}
Copy link

ghost commented Sep 16, 2015

Thank you! And the Spring-Bean configuration version is here: http://docs.spring.io/spring-integration/reference/html/http.html#http-proxy.

@qyvlik
Copy link

qyvlik commented May 24, 2019

what about socks proxy?

@ftokarev
Copy link

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