Spring RestTemplate With Auth Token, Proxy and Timeout

Introduction

Here I am going to tell you how to use proxy server and timeout with Spring Boot RestTemplate API. If you are running your application behind a proxy server then you need to connect to REST API through proxy server and without proxy server connection you may face connection timeout error or other errors. Remember if you are behind the proxy server, setting connection timeout or reads timeout or connection request timeout won’t help your application and in this case your application won’t be able to connect to the server API.

RestTemplate is used to consume the REST APIs or services in your application. RestTemplate provides a list of methods which can be used at your convenience for calling GET, POST, DELETE, PUT, etc. based APIs by simply passing the required arguments.

How to find proxy?

In windows system you can find proxy in various methods. You can use the command netsh winhttp show proxy in the command line tool (cmd prompt). You can also open the proxy settings in your system’s browser and find the proxy address and port.

In Linux based system you also have various ways to find the proxy. You can use echo “$http_proxy” for HTTP or echo “$https_proxy” for HTTPS. You can use the command env | grep proxy to find the proxy server details. You can also use the command netstat -na in shell terminal to find the proxy server details.

Related Post:

Prerequisites

Java 1.8+, Maven 3.8.2, Spring Boot 2.6.1

RestTemplate with Proxy and Timeout

Here I will show you two ways of creating an instance from RestTemplate. One is using the RestTemplateBuilder and another one using the new operator or keyword. In some situations, using RestTemplateBuilder has the advantage over new operator. You can use builder design pattern why it is effective in some situations.

Using RestTemplateBuilder The following code is used to build a RestTemplate instance:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
 
              HttpHost httpHost = new HttpHost("proxy-cloud.example.com", 8080);
 
              HttpClientBuilder clientBuilder = HttpClientBuilder.create();
              clientBuilder.setProxy(httpHost);
 
              HttpClient httpClient = clientBuilder.build();
 
              HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
              // factory.setHttpClient(httpClient);
              factory.setConnectionRequestTimeout(1000);
              factory.setConnectTimeout(1000);
              factory.setReadTimeout(1000);
 
              return builder.requestFactory(() -> factory).build();
}

In the above code, I have created instance of HttpHost to use it as a proxy server instance. The instance from HttpComponentsClientHttpRequestFactory is used to set the proxy server and various timeout options for the RestTemplate.

Using new operator The following code is used to create an instance from RestTemplate using new operator. The code almost similar to the above one and here new operator is used instead of builder.

@Bean
public RestTemplate restTemplate() {
              HttpHost httpHost = new HttpHost("proxy-cloud.example.com", 8080);
 
              HttpClientBuilder clientBuilder = HttpClientBuilder.create();
              clientBuilder.setProxy(httpHost);
 
              HttpClient httpClient = clientBuilder.build();
 
              HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
              // factory.setHttpClient(httpClient);
              factory.setConnectionRequestTimeout(1000);
              factory.setConnectTimeout(1000);
              factory.setReadTimeout(1000);
 
              return new RestTemplate(factory);
}

If you want you can use the setter for httpClient object instead of passing it in the constructor of HttpComponentsClientHttpRequestFactory.

Calling REST APIs

The following code shows how to consume external REST APIs using RestTemplate instance.

@RestController
public class RestApiController {
 
              @Autowired
              private RestTemplate restTemplate;
 
              @GetMapping("/fetch")
              public ResponseEntity<Object> fetchSomething() {
                             Object response = restTemplate.getForObject("url of the REST API", Object.class);
 
                             return new ResponseEntity<Object>(response, HttpStatus.OK);
              }
 
              @PostMapping("/create")
              public ResponseEntity<Object> createSomething(@RequestBody Object obj) {
                             HttpHeaders httpHeaders = new HttpHeaders();
                             httpHeaders.set("Content-Type", "application/json");
                             httpHeaders.set("Authorization", "Bearer token value");
 
                             Object request = new Object();
 
                             HttpEntity<Object> httpEntity = new HttpEntity<Object>(request, httpHeaders);
 
                             Object response = restTemplate.postForObject("url of the REST API", httpEntity, Object.class);
 
                             return new ResponseEntity<Object>(response, HttpStatus.OK);
              }
 
}

Note in the above code I have used Object for both request and response types. Use your appropriate objects to replace them to get the response. This example has been written based on the practical project and actual REST API URLs, proxy server details and other stuffs have been removed due to security reasons.

Hope this example gave you an idea about how to use proxy server details and timeouts with your RestTemplate object wherever applicable during external service consumption.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *