[Spring framework] HTTP request error handling by RestTemplate when using a proxy server

Overview

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.

Event that occurred

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.

Error message


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

Image diagram (network environment)

proxy.png

Cause

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.

How to set proxy settings in Spring Boot application

1. Use System.setProperty

//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");

2. Specify as an argument when starting the JVM

Specify as a runtime argument of Spring application

java ./application.jar -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

3. Set using factory when creating an instance of RestTemplate

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

Reference link

Recommended Posts

[Spring framework] HTTP request error handling by RestTemplate when using a proxy server
Error handling when Gradle dependency is using SLF4J
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot
[Java] How to get a request by HTTP communication
Error when using SnapKit