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

The logs of the kubelet service

Develop a Kafka producer to send messages to a Kafka topic

Parasite of korean movie

리눅스의 부팅과정 (프로세스, 서비스 관리)

difference between truncate and truncate_preserve in hbase

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

To create a drawer in the footer using Tailwind CSS

To switch to a specific tag in a Git repository

Kafka consumer in a Spring Boot application using a scheduled task