Spring RestTemplate 示例
Spring RestTemplate 提供了一种方便的方法来测试RESTful Web 服务。
Spring Rest模板
- Spring RestTemplate 类是的一部分
spring-web
,在 Spring 3 中引入。 - 我们可以使用 RestTemplate 来测试基于 HTTP 的 Restful Web 服务,它不支持 HTTPS 协议。
- RestTemplate 类为不同的 HTTP 方法提供了重载方法,例如 GET、POST、PUT、DELETE 等。
Spring RestTemplate 示例
让我们看一下 Spring RestTemplate 示例,我们将在其中测试在Spring Data JPA文章中创建的 REST Web 服务。下表说明了此 REST Web 服务支持的 URI。 .tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-baqh{文本对齐:中心;垂直对齐:顶部} .tg .tg-yw4l{垂直对齐:顶部}
URI | HTTP 方法 | 描述 |
---|---|---|
/springData/人 | 得到 | 从数据库获取所有人员 |
/ springData / person / {id} | 得到 | 根据 ID 获取人员 |
/springData/人 | 邮政 | 将人员添加到数据库 |
/springData/人 | 放 | 更新人员 |
/ springData / person / {id} | 删除 | 根据 ID 删除人员 |
让我们开始创建 Rest 客户端项目来测试这些 Web 服务。下图显示了我们最终的 Spring RestTemplate 示例项目。
Spring RestTemplate Maven 依赖项
我们需要Spring 框架的依赖项spring-core
。然后我们需要包含类的工件。我们还需要通过Jackson API获得Spring JSON支持。spring-context
spring-web
RestTemplate
jackson-mapper-asl
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.spring</groupId>
<artifactId>SpringRestTemplate</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.framework>4.3.0.RELEASE</spring.framework>
<spring.web>3.0.2.RELEASE</spring.web>
<serializer.version>2.8.1</serializer.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.web}</version>
</dependency>
</dependencies>
</project>
Spring 配置类
我们必须为 RestTemplate 类定义一个spring bean,这是在AppConfig
类中完成的。
package com.journaldev.spring.config;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
@ComponentScan("com.journaldev.spring")
public class AppConfig {
@Bean
RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
restTemplate.getMessageConverters().add(converter);
return restTemplate;
}
}
请注意,RestTamplate 使用 MessageConverter,我们需要在 RestTemplate bean 中设置此属性。在我们的示例中,我们使用MappingJacksonHttpMessageConverter
它来从 JSON 格式获取数据。
模型类
由于我们尝试使用 jackson mapper 将 Web 服务返回的 JSON 转换为 Java 对象,因此我们必须为此创建模型类。请注意,此模型类与 Web 服务中使用的模型类非常相似,只是这里我们不需要 JPA 注释。
package com.journaldev.spring.model;
public class Person {
private Long id;
private Integer age;
private String firstName;
private String lastName;
public Person() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", age=" + age + ", firstName='" + firstName + '\'' + ", lastName='" + lastName
+ '\'' + '}';
}
}
Spring RestTemplate 客户端类
最后一步是创建将使用上面定义的 RestTemplate bean 的客户端类。
package com.journaldev.spring.config;
import java.util.List;
import org.springframework.http.HttpStatus;
import com.journaldev.spring.model.Person;
public interface PersonClient {
List<Person> getAllPerson();
Person getById(Long id);
HttpStatus addPerson(Person person);
void updatePerson(Person person);
void deletePerson(Long id);
}
package com.journaldev.spring.config;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.journaldev.spring.model.Person;
@Service
public class PersonClientImpl implements PersonClient {
@Autowired
RestTemplate restTemplate;
final String ROOT_URI = "https://localhost:8080/springData/person";
public List<Person> getAllPerson() {
ResponseEntity<Person[]> response = restTemplate.getForEntity(ROOT_URI, Person[].class);
return Arrays.asList(response.getBody());
}
public Person getById(Long id) {
ResponseEntity<Person> response = restTemplate.getForEntity(ROOT_URI + "/"+id, Person.class);
return response.getBody();
}
public HttpStatus addPerson(Person person) {
ResponseEntity<HttpStatus> response = restTemplate.postForEntity(ROOT_URI, person, HttpStatus.class);
return response.getBody();
}
public void updatePerson(Person person) {
restTemplate.put(ROOT_URI, person);
}
public void deletePerson(Long id) {
restTemplate.delete(ROOT_URI + id);
}
}
代码是自我理解的,我们根据 URI 和 HTTP 方法调用 RestTemplate 方法,并在需要时传递适当的请求对象。
Spring RestTemplate 测试类
It’s time to test our Spring RestTemplate example project, below class shows how to use RestTemplate methods in Spring way.
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;
import com.journaldev.spring.config.AppConfig;
import com.journaldev.spring.config.PersonClient;
import com.journaldev.spring.model.Person;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
PersonClient client = applicationContext.getBean(PersonClient.class);
System.out.println("Getting list of all people:");
for (Person p : client.getAllPerson()) {
System.out.println(p);
}
System.out.println("\nGetting person with ID 2");
Person personById = client.getById(2L);
System.out.println(personById);
System.out.println("Adding a Person");
Person p = new Person();
p.setAge(50);
p.setFirstName("David");
p.setLastName("Blain");
HttpStatus status = client.addPerson(p);
System.out.println("Add Person Response = " + status);
applicationContext.close();
}
}
When I run above program against my local setup, I get following output.
Getting list of all people:
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Person{id=1, age=30, firstName='Vlad', lastName='Mateo'}
Getting person with ID 2
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Adding a Person
Add Person Response = 201
Below image shows the web service database table data before and after executing above program. As you can see that the program output matches with the sample table data. That’s all for Spring RestTemplate example, you can download the project from below link.
Download Spring RestTemplate Example Project
Reference: API Doc