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
HTTP Methods:
getForObject()
– For simple GET requests.postForObject()
– For POST requests with request body.exchange()
– For complex requests with full control (headers, methods, etc.).
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.
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(); }
- Add logging or headers by creating a
Timeouts:
- Configure connection and read timeouts using
RestTemplateBuilder
.
- Configure connection and read timeouts using
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.
댓글
댓글 쓰기