10 Examples Of RestTemplate In Spring
In Spring, the RestTemplate is basically a class that is designed according to the same principles as the many other Spring Template classes like JdbcTemplate and JmsTemplate. It will provide you a very simplified approach along with some default behaviors that can be used for performing complex tasks.
The RestTemplate class is actually a synchronous client that is designed to call REST services. Therefore, its primary methods are also closely related to REST's underpinnings.
You will eventually get used to the HTTP protocol methods like HEAD, GET, DELETE, PUT, POST, and OPTIONS.
1. Building RestTemplate using RestTemplateBuilder
public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder .setConnectTimeout(Duration.ofMillis(3000)) .setReadTimeout(Duration.ofMillis(3000)) .build(); }
2. Building RestTemplate Using SimpleClientHttpRequestFactory
public RestTemplate restTemplate() { var factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(3000); factory.setReadTimeout(3000); return new RestTemplate(factory); }
3. Building RestTemplate Using Apache HTTPClient
@Autowired CloseableHttpClient httpClient; @Value("${api.host.baseurl}") private String apiHost; @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost)); return restTemplate; } @Bean @ConditionalOnMissingBean public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() { HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setHttpClient(httpClient); return clientHttpRequestFactory; }
4. How To Inject The RestTemplate Bean
@Autowired private RestTemplate restTemplate;
5. Consuming Responses (String)
private final String URI_USERS_ID = "/users/{id}"; @Autowired RestTemplate restTemplate; //Using RestTemplate Map<String, String> params = new HashMap<String, String>(); params.put("id", "1"); //Parse the string after getting the response String userStr = restTemplate.getForObject(URI_USERS_ID, String.class, params);
6. Consuming Responses to POJO
private final String URI_USERS = "/users"; private final String URI_USERS_ID = "/users/{id}"; @Autowired RestTemplate restTemplate; //Using RestTemplate // "users" User[] usersArray = restTemplate.getForObject(URI_USERS, User[].class); // "users/{id}" Map<String, String> params = new HashMap<String, String>(); params.put("id", "1"); User user = restTemplate.getForObject(URI_USERS_ID, User.class, params);
private final String URI_USERS = "/users"; private final String URI_USERS_ID = "/users/{id}"; @Autowired RestTemplate restTemplate; //Using RestTemplate // "users" ResponseEntity<User[]> responseEntity = restTemplate .getForEntity(URI_USERS, User[].class); // "users/{id}" Map<String, String> params = new HashMap<String, String>(); params.put("id", "1"); ResponseEntity<User> responseEntity = restTemplate .getForEntity(URI_USERS_ID, User.class, params);
6. Sending HTTP Headers
private final String URI_USERS = "/users"; @Autowired RestTemplate restTemplate; //Using RestTemplate HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("X-COM-PERSIST", "NO"); headers.set("X-COM-LOCATION", "USA"); HttpEntity<String> entity = new HttpEntity<String>(headers); ResponseEntity<User[]> responseEntity = restTemplate .exchange(URI_USERS, HttpMethod.GET, entity, User[].class);
7. How to Send URL Parameters In Spring
Map<String, String> params = new HashMap<String, String>(); params.put("id", "1"); ResponseEntity<User> responseEntity = restTemplate .getForEntity(URI_USERS_ID, User.class, params);
8. Consuming A POST API
private final String URI_USERS = "/users"; @Autowired RestTemplate restTemplate; //Using RestTemplate User newUser = new User(1, "Alex", "Golan", "a@mail.com"); User createdUser = restTemplate.postForObject(URI_USERS, newUser, User.class); //Use the object as needed
9. How to Consume a PUT API
private final String URI_USERS_ID = "/users/{id}"; @Autowired RestTemplate restTemplate; //Using RestTemplate Map<String, String> params = new HashMap<String, String>(); params.put("id", "2"); User updatedUser = new User(1, "Alex", "Golan", "a@mail.com"); User user = restTemplate.put(URI_USERS_ID, updatedUser, User.class); //Use the object as needed
10. How to Consume A DELETE API
private final String URI_USERS_ID = "/users/{id}"; @Autowired RestTemplate restTemplate; Map<String, String> params = new HashMap<String, String>(); params.put("id", "2"); //Using RestTemplate restTemplate.delete ( URI_USERS_ID, params );
RestTemplate Frequently Asked Questions
Conclusion
- 7 Best Courses to learn Spring Framework (best courses)
- How to create a REST client using the Spring framework in Java? (tutorial)
- Top 5 Books to learn RESTful APIs and Web Services (books)
- 10 Free Courses to learn Spring Boot (Free Courses)
- My Favorite Courses to learn Software Architecture (courses)
- Spring HelloWorld Example using Dependency Injection (tutorial)
- How to convert a JSON array to a String array in Java? (tutorial)
- Top 5 courses to learn GraphQL for Beginners (courses)
- Top 10 REST Web Service Interview Questions (answer)
- Top 5 Courses to learn RESTFul Web Services in Java? (courses)
- Difference between Idempotent and safe methods in HTTP? (answer)
- Difference between REST and SOAP Web Services? (answer)
- How to create a JDBC connection pool using Spring? (tutorial)
- Difference between PUT vs POST in REST Web Service? (article)
- Top 10 Courses to learn Microservices for Java developers (courses)
Thanks for reading this article so far. If you like this tutorial of sending HTTP requests from the Java Program using RestTemplate then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.