An error occurred when I tried to send a request to an external API using Spring RestTemplate in a network environment where the Internet is accessed using a proxy server.
In the environment I usually develop, I do not use a proxy server and it took a long time to investigate, so I will make a note of the method supported this time.
The following error occurred when I made a GET request using an external API using RestTemplate.exchange
in a network environment where the Internet was accessed using a proxy server.
However, when I accessed the same API with a browser (Chrome), the response was returned properly.
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "{targetURL}":
Connection refused: connect;
nested exception is java.net.ConnectException: Connection refused: connect
Since the browser used the proxy settings of the host server, it was possible to access via the proxy server when accessing the Internet, but the Spring Boot application side was not able to access via the proxy server when making a request.
On the Spring Boot application side, it seems that the proxy server cannot be used unless the proxy settings are explicitly made in the configuration file and runtime arguments.
//In this case webcache as a proxy server.example.com:Use 8080
//For https, https.proxyHost, https.Use proxyPort
System.setProperty("http.proxyHost", "webcache.example.com");
System.setProperty("http.proxyPort", "8080");
Specify as a runtime argument of Spring application
java ./application.jar -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
Methods 1 and 2 affect the entire system, so use this method if you want to limit the range of influence.
//Set proxy settings here
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
//Prepare ClientHttpRequestFactory to set proxy for RestTermplate
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
RestTemplate restTemplate = new RestTemplate(requestFactory);
//HTTP using this Rest Template(S)Communicate
Recommended Posts