Spring RestTemplate示例

时间:2020-02-23 14:36:00  来源:igfitidea点击:

Spring RestTemplate提供了一种方便的方法来测试RESTful Web服务。

SpringRestTemplate

  • Spring RestTemplate类是Spring 3中引入的spring-web的一部分。

  • 我们可以使用RestTemplate测试基于HTTP的静态Web服务,它不支持HTTPS协议。

  • RestTemplate类为不同的HTTP方法提供了重载的方法,例如GET,POST,PUT,DELETE等。

Spring RestTemplate示例

让我们看一下Spring RestTemplate示例,在这里我们将测试Spring Data JPA文章中创建的REST Web服务。
下表说明了此其余Web服务支持的URI。

URIHTTP MethodDescription
/springData/personGETGet all persons from database
/springData/person/{id}GETGet person by id
/springData/personPOSTAdd person to database
/springData/personPUTUpdate person
/springData/person/{id}DELETEDelete person by id

让我们开始创建Rest客户项目来测试这些网络服务。

下图显示了我们最终的Spring RestTemplate示例项目。

Spring RestTemplate Maven依赖关系

我们需要spring框架的spring-core和spring-context依赖项。
然后,我们需要包含" RestTemplate"类的" spring-web"工件。
我们还需要Hymanson-mapper-asl通过Hymanson API获得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.theitroad.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.Hymanson</groupId>
			<artifactId>Hymanson-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.theitroad.spring.config;

import org.codehaus.Hymanson.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.MappingHymansonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
@ComponentScan("com.theitroad.spring")
public class AppConfig {

	@Bean
	RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		MappingHymansonHttpMessageConverter converter = new MappingHymansonHttpMessageConverter();
		converter.setObjectMapper(new ObjectMapper());
		restTemplate.getMessageConverters().add(converter);
		return restTemplate;
	}
}

请注意,RestTamplate使用MessageConverter,我们需要在RestTemplate bean中设置此属性。
在我们的示例中,我们使用" MappingHymansonHttpMessageConverter"从JSON格式中获取数据。

模型类

由于我们正在尝试使用Hymanson 映射器将Web服务返回的JSON转换为java对象,因此我们必须为此创建模型类。
请注意,该模型类将与网络服务中使用的模型类非常相似,除了这里我们不需要JPA批注。

package com.theitroad.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.theitroad.spring.config;

import java.util.List;

import org.springframework.http.HttpStatus;

import com.theitroad.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.theitroad.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.theitroad.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测试类

是时候测试我们的Spring RestTemplate示例项目了,下面的类展示了如何以Spring方式使用RestTemplate方法。

package com.theitroad.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;

import com.theitroad.spring.config.AppConfig;
import com.theitroad.spring.config.PersonClient;
import com.theitroad.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();
	}
}

当我针对本地设置运行上述程序时,得到以下输出。

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