Using Spring RestTemplate for GET, POST, PUT, and DELETE Requests in Spring Boot
This article explains how to use Spring's RestTemplate to perform GET, POST, PUT, and DELETE HTTP calls, compares getForObject with getForEntity, demonstrates parameter passing styles, and shows how to handle redirects with postForLocation, providing complete code examples for each operation.
Java provides many HTTP client options such as HttpUrlConnection, HttpClient, OkHttp, and the Spring‑provided RestTemplate, which is the focus of this tutorial.
RestTemplate, introduced in Spring 3.0, is independent of Spring Boot and Spring Cloud and implements the RestOperations interface, offering common REST methods like GET, POST, PUT, DELETE, as well as exchange and execute.
GET Requests
In the provider, a simple @GetMapping("/hello2") endpoint is defined:
@GetMapping("/hello2")
public String hello2(String name) {
return "hello " + name;
}The consumer can call this endpoint using RestTemplate's GET methods. Two main families of methods exist: getForObject – returns the response body directly. getForEntity – returns a ResponseEntity containing the body, status code, and headers.
Example of using both methods:
String s1 = restTemplate.getForObject("http://provider/hello2?name={1}", String.class, "javaboy");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://provider/hello2", String.class, "javaboy");
String body = responseEntity.getBody();
HttpStatus statusCode = responseEntity.getStatusCode();
int statusCodeValue = responseEntity.getStatusCodeValue();
HttpHeaders headers = responseEntity.getHeaders();
for (String s : headers.keySet()) {
System.out.println(s + ":" + headers.get(s));
}Three overloads are available for each method, supporting different ways of passing parameters (positional, map, or URI).
POST Requests
A shared commons module defines a User class used by both provider and consumer. The provider exposes two POST endpoints:
@PostMapping("/user1")
public User addUser1(User user) {
return user;
}
@PostMapping("/user2")
public User addUser2(@RequestBody User user) {
return user;
}In the consumer, postForObject is used to send either a MultiValueMap (key/value form) or a POJO (JSON form):
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("username", "javaboy");
map.add("password", "123");
map.add("id", 99);
User user = restTemplate.postForObject("http://provider/user1", map, User.class);
System.out.println(user);
user.setId(98);
user = restTemplate.postForObject("http://provider/user2", user, User.class);
System.out.println(user);The additional method postForLocation returns the URI of a 302 redirect, useful for scenarios like user registration followed by immediate login.
URI uri = restTemplate.postForLocation("http://provider/register", map);
String s = restTemplate.getForObject(uri, String.class);
System.out.println(s);PUT Requests
The provider defines two PUT endpoints that accept either key/value parameters or a JSON body:
@PutMapping("/user1")
public void updateUser1(User user) { System.out.println(user); }
@PutMapping("/user2")
public void updateUser2(@RequestBody User user) { System.out.println(user); }The consumer calls them similarly to POST, using either a MultiValueMap or a POJO:
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("username", "javaboy");
map.add("password", "123");
map.add("id", 99);
restTemplate.put("http://provider/user1", map);
User user = new User();
user.setId(98);
user.setUsername("zhangsan");
user.setPassword("456");
restTemplate.put("http://provider/user1", user);DELETE Requests
The provider offers two delete endpoints, one accepting a query parameter and the other using a @PathVariable:
@DeleteMapping("/user1")
public void deleteUser1(Integer id) { System.out.println(id); }
@DeleteMapping("/user2/{id}")
public void deleteUser2(@PathVariable Integer id) { System.out.println(id); }The consumer can delete using either positional arguments or a map, just like GET:
restTemplate.delete("http://provider/user1?id={1}", 99);
restTemplate.delete("http://provider/user2/{1}", 99);Overall, the tutorial demonstrates the full lifecycle of RESTful interactions with Spring's RestTemplate, covering request creation, response handling, parameter passing styles, and redirect processing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
