springrestemplate提供了一种方便的测试方法RESTful web服务.
目录
Spring RestTemplate
- SpringRestTemplate类是
spring-web
, introduced in Spring 3. - 我们可以使用restemplate来测试基于HTTP的restfulweb服务,它不支持HTTPS协议。
- restemplate类提供超载方法用于不同的HTTP方法,如GET、POST、PUT、DELETE等。
Spring restemplate示例
让我们看看SpringRestTemplate示例,我们将在其中测试在中创建的RESTWeb服务Spring数据JPA文章。下表说明了这个restweb服务支持的uri。
.tg{边框-折叠:折叠;边框间距:0;边框颜色:#999;}.tg td{font-系列:Arial,无衬线字体-尺寸:14px;填充:10px 5px;边框-样式:实心;边框宽度:1倍;溢出:隐藏;分词:普通;边框颜色:#999;颜色:#444;背景色:#F7FDFA;}.tg th{font-系列:Arial,无衬线字体-大小:14px;字体粗细:正常;填充:10px 5px;边框样式:实心;边框-宽度:1px;溢出:隐藏;单词-打断:法线;边框颜色:#999;颜色:#fff;背景色:#26ADE4;}.tg.tg baqh{文本-对齐:居中;垂直对齐:顶部}.tg.tg-yw4l{垂直-对齐:顶部}
URI | HTTP方法 | 说明 |
---|---|---|
/springData/人 | 得到 | 从数据库中获取所有人员 |
/springData/person/{id} | 得到 | 按id获取人员 |
/springData/人 | 岗位 | 将人员添加到数据库 |
/springData/人 | 把 | 更新人员 |
/springData/person/{id} | 删除 | 按id删除人员 |
让我们开始创建Rest客户机项目来测试这些web服务。
下图显示了我们最后的springrestemplate示例项目。
springrestemplate Maven依赖项
我们需要spring-core
, spring-context
dependencies for spring框架. 那我们需要spring-web
artefact that contains RestTemplate
class. We also need jackson-mapper-asl
for Spring JSON支持通过杰克逊应用程序编程接口。
<?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配置类
我们必须定义一个Spring Bean对于restemplate类,在AppConfig
class.
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;
}
}
注意restamplate使用MessageConverter,我们需要在restemplatebean中设置这个属性。在我们的示例中,我们使用MappingJacksonHttpMessageConverter
for fetching data from JSON format.
模型类
由于我们试图使用jackson映射器将web服务返回的JSON转换为java对象,因此我们必须为此创建模型类。注意,这个model类与web服务中使用的model类非常相似,只是这里不需要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 restemplate客户端类
最后一步是创建将使用上面定义的restemplatebean的客户机类。
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方法调用restemplate方法,如果需要,通过传递适当的请求对象。
Spring restemplate测试类
现在是测试springrestemplate示例项目的时候了,下面的类将演示如何以Spring方式使用restemplate方法。
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("
Getting 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();
}
}
当我针对本地设置运行上述程序时,我得到以下输出。
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
下图显示了执行上述程序前后的web服务数据库表数据。
如您所见,程序输出与示例表数据相匹配。这是所有针对springrestemplate的例子,您可以从下面的链接下载项目。
参考文献:API文件