By default, RestTemplate don’t use a proxy to make the http calls and if you work in an environment that requires one, you will encounter the following exception :
1 2 3 4 5 6 7 8 |
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://roufid.com": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:633) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:588) at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:295) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) ... 33 more |
This tutorial will show two ways to fix it.
Defining the proxy in RestTemplate
The first way to solve the problem is by setting a proxy in the RestTemplate object as the following :
1 2 3 4 5 |
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your.proxy.server", 80)); clientHttpReq.setProxy(proxy); RestTemplate restTemplate = new RestTemplate(clientHttpReq); |
Defining the proxy in the System properties
Another solution to set the proxy is by defining it in the system properties as below :
1 2 3 |
Properties props = System.getProperties(); props.put("http.proxyHost", "your.proxy.server"); props.put("http.proxyPort", "80"); |