How to use Spring RestTemplate
1) Overview
This is a tutorial about how to consume REST service using Spring RestTemplate. You can find here user service application that we are going to use as a REST service.
Using this, we can call 3rd party REST services or use for implementing microservices.
2) Dependencies
We need the following dependency to work with Spring RestTemplate.
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
|
Other than that dependency, we will use the jackson-fasterxml dependency for convert JSON to/from Object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mydevgeek</groupId>
<artifactId>rest-template-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>rest-template-service</name>
<description>Demo Rest Template Service</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
|
3) Use GET
3.1) To retrieve a Java Object
Using getForObject(),
directrly convert to the Object.
|
String url = "http://localhost:8080/user/1";
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject(url, User.class);
System.out.println("GET User :" + user.getFirstName() + " " + user.getLastName());
|
3.2) Pass parameters
Using HashMap, we can pass a parameters also.
|
String url = "http://localhost:8080/user/{id}";
Map<String, String> params = new HashMap<>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject(url, User.class, params);
System.out.println("GET User :" + user.getFirstName() + " " + user.getLastName());
|
3.2) Get response as a String and convert to the Java Object
|
String url = "http://localhost:8080/user/1";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = restTemplate.headForHeaders(url);
ResponseEntity response = restTemplate.getForEntity(url, String.class);
System.out.println(response);
|
output
|
<200 OK,{"id":1,"firstName":"John","lastName":"Doe"},{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Mon, 01 May 2017 15:01:07 GMT]}>
|
convert String to Java Object.
|
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(response.getBody(), User.class);
|
4) Use POST
Normally, The POST method uses for creating a new resource. We’ll create a new user using the POST method.
|
String url = "http://localhost:8080/user";
User user = new User();
user.setId(1L);
user.setFirstName("John");
user.setLastName("Doe");
RestTemplate restTemplate = new RestTemplate();
User result = restTemplate.postForObject(url, user, User.class);
System.out.println(result.getFirstName() + " " + result.getLastName());
|
5) Use PUT
PUT method use for updating a exist resource.
1
2
3
4
5
6
7
8
9
10
11
12
|
String url = "http://localhost:8080/user/{id}";
Map<String, String> params = new HashMap<>();
params.put("id", "1");
User user = new User();
user.setId(1L);
user.setFirstName("John");
user.setLastName("Smith");
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(url, user, params);
|
6) Use DELETE
We can use the DELETE method for removing a resource.
|
String url = "http://localhost:8080/user/{id}";
Map<String, String> params = new HashMap<>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(url, params);
|
7) Using exchange()
We can use the exchange()
with all HTTP methods above mentioned.
7.1) Using exchange send POST request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
String url = "http://localhost:8080/user";
RestTemplate restTemplate = new RestTemplate();
User user = new User();
user.setId(1L);
user.setFirstName("John");
user.setLastName("Smith");
HttpEntity<User> request = new HttpEntity<>(user);
ResponseEntity<User> response = restTemplate
.exchange(url, HttpMethod.POST, request, User.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
|
7.2) Using AsyncRestTemplate
Using AsyncRestTemplate
, send REST calls asynchronously.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
String url = "http://localhost:8080/user";
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
User user = new User();
user.setId(1L);
user.setFirstName("John");
user.setLastName("Smith");
HttpEntity<User> request = new HttpEntity<>(user);
ListenableFuture<ResponseEntity<String>> response = restTemplate
.exchange(url, HttpMethod.POST, request, String.class);
response.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
@Override
public void onFailure(Throwable throwable) {
//do something
}
@Override
public void onSuccess(ResponseEntity<String> response) {
System.out.println(response.getBody());
}
});
|
Complete examples find here.