Creating an synchronous HTTP request using Spring RestTemplate

While RestTemplate is now in maintenance mode and WebClient is recommended for new applications, it’s still widely used in existing projects. Here’s how you can configure and use RestTemplate in a Spring Boot application:


1. Add Dependencies

Ensure the following dependency is present in your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Configure a RestTemplate Bean

Define a RestTemplate bean in a configuration class to enable dependency injection:

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(5)) // Connection timeout
                .setReadTimeout(Duration.ofSeconds(10))   // Read timeout
                .build();
    }
}

3. Use RestTemplate in a Service

Here’s how to use RestTemplate to make HTTP requests:

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData(String url) {
        return restTemplate.getForObject(url, String.class);
    }
}

4. Example REST Controller

Here’s an example of calling the service from a REST controller:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    private final ApiService apiService;

    public ApiController(ApiService apiService) {
        this.apiService = apiService;
    }

    @GetMapping("/fetch")
    public String fetch(@RequestParam String url) {
        return apiService.fetchData(url);
    }
}

Features and Options with RestTemplate

  1. HTTP Methods:

    • getForObject() – For simple GET requests.
    • postForObject() – For POST requests with request body.
    • exchange() – For complex requests with full control (headers, methods, etc.).
  2. Error Handling:

    • Use ResponseErrorHandler for custom error handling:

      @Bean
      public RestTemplate restTemplate(RestTemplateBuilder builder) {
          return builder.errorHandler(new CustomResponseErrorHandler()).build();
      }
      
    • Implement the ResponseErrorHandler interface to handle HTTP errors.

  3. Custom Interceptors:

    • Add logging or headers by creating a ClientHttpRequestInterceptor:
      @Bean
      public RestTemplate restTemplate(RestTemplateBuilder builder) {
          return builder
                  .additionalInterceptors((request, body, execution) -> {
                      // Modify request headers or log details
                      return execution.execute(request, body);
                  })
                  .build();
      }
      
  4. Timeouts:

    • Configure connection and read timeouts using RestTemplateBuilder.

This setup allows you to use RestTemplate with dependency injection while adhering to best practices for configuration and error handling. If you're starting a new project, consider using WebClient for a more modern, reactive approach.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

Install and run an FTP server using Docker

Sorting on an aggregation in Elasticsearch

Fundamentals of English Grammar #1

티베트-버마어파 와 한어파(중국어파)의 어순 비교

Resetting a Kafka topic, 카프카 토픽 초기화

오늘의 문장2

dagrun_timeout of Airflow

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

[Ubuntu] *.deb 파일 설치 방법