# Spring `RestTemplate` – Spring REST 客户端示例

> 原文： [https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/](https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/)

在学习为[ XML 表示形式](https://howtodoinjava.com/spring/spring-restful/spring-rest-hello-world-xml-example/)和[ JSON 表示形式](https://howtodoinjava.com/spring/spring-restful/spring-rest-hello-world-json-example/)构建 **Spring REST API** 之后，让我们构建 **Spring REST 客户端**以使用我们编写的 API 在链接的示例中。

在 Spring 应用程序内部访问第三方 REST 服务的过程涉及 Spring [`RestTemplate`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html)类的使用。 `RestTemplate`类的设计原理与许多其他 Spring `*Template`类（例如`JdbcTemplate`和`JmsTemplate`）相同，为执行复杂任务提供了具有默认行为的简化方法。

鉴于`RestTemplate`类是为调用 REST 服务设计的，因此它的主要方法与 REST 的基础紧密结合在一起就不足为奇了，REST 的基础是 HTTP 协议的方法： **HEAD**， **GET** ， **POST** ， **PUT** ， **DELETE** 和 **OPTION**。 例如，`RestTemplate`类具有方法`headForHeaders()`，`getForObject()`，`postForObject()`，`put()`和`delete()`等。

> 阅读更多和源代码： [Spring REST 示例 – JSON](https://howtodoinjava.com/spring/spring-restful/spring-rest-hello-world-json-example/)

> 阅读更多：[带有`HttpClient`的`RestTemplate` Java 配置](https://howtodoinjava.com/spring/spring-restful/resttemplate-httpclient-java-config/)

## 1\. Spring `RestTemplate` – HTTP GET 方法示例

#### 1.1. XML 响应

**REST API 代码**

用于 HTTP GET 方法的 Spring REST API。

```java
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public String getAllEmployeesXML(Model model) 
{
	model.addAttribute("employees", getEmployeesCollection());
	return "xmlTemplate";
}

```

**REST 客户端代码**

Spring REST 客户端使用`RestTemplate`访问 HTTP GET api 请求。

```java
private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees.xml";

	RestTemplate restTemplate = new RestTemplate();
	String result = restTemplate.getForObject(uri, String.class);

	System.out.println(result);
}

```

#### 1.2. JSON 响应

**REST API 代码**

```java
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String getAllEmployeesJSON(Model model) 
{
	model.addAttribute("employees", getEmployeesCollection());
	return "jsonTemplate";
}

```

**REST 客户端代码**

```java
private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees.json";

	RestTemplate restTemplate = new RestTemplate();
	String result = restTemplate.getForObject(uri, String.class);

	System.out.println(result);
}

```

#### 1.3. 使用`RestTemplate`的自定义 HTTP 标头

**REST API 代码**

```java
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String getAllEmployeesJSON(Model model) 
{
	model.addAttribute("employees", getEmployeesCollection());
	return "jsonTemplate";
}

```

**REST 客户端代码**

```java
private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";

	RestTemplate restTemplate = new RestTemplate();

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
	HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

	ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

	System.out.println(result);
}

```

#### 1.4. 获取响应作为对象

**REST API 代码**

```java
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public String getAllEmployeesXML(Model model) 
{
	model.addAttribute("employees", getEmployeesCollection());
	return "xmlTemplate";
}

```

**REST 客户端代码**

```java
private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";
	RestTemplate restTemplate = new RestTemplate();

	EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class);

	System.out.println(result);
}

```

#### 1.5. URL 参数

**REST API 代码**

```java
@RequestMapping(value = "/employees/{id}")
public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id) 
{
	if (id <= 3) {
		EmployeeVO employee = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com");
		return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
	}
	return new ResponseEntity(HttpStatus.NOT_FOUND);
}

```

**REST 客户端代码**

```java
private static void getEmployeeById()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";

	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "1");

	RestTemplate restTemplate = new RestTemplate();
	EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params);

	System.out.println(result);
}

```

## 2\. Spring `RestTemplate` – HTTP POST 方法示例

**REST API 代码**

用于 HTTP POST 方法的 Spring REST API。

```java
@RequestMapping(value = "/employees", method = RequestMethod.POST)
public ResponseEntity<String> createEmployee(@RequestBody EmployeeVO employee) 
{
	System.out.println(employee);
	return new ResponseEntity(HttpStatus.CREATED);
}

```

**REST 客户端代码**

Spring REST 客户端使用`RestTemplate`访问 HTTP POST api 请求。

```java
private static void createEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees";

	EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly", "test@email.com");

	RestTemplate restTemplate = new RestTemplate();
	EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);

	System.out.println(result);
}

```

## 3\. Spring `RestTemplate` – HTTP PUT 方法示例

**REST API 代码**

用于 HTTP PUT 方法的 Spring REST API。

```java
@RequestMapping(value = "/employees/{id}", method = RequestMethod.PUT)
public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id") int id, @RequestBody EmployeeVO employee) 
{
	System.out.println(id);
	System.out.println(employee);
	return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
}

```

**REST 客户端代码**

Spring REST 客户端使用`RestTemplate`访问 HTTP PUT api 请求。

```java
private static void updateEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";

	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "2");

	EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly", "test@email.com");

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.put ( uri, updatedEmployee, params);
}

```

## 4\. Spring `RestTemplate` – HTTP DELETE 方法示例

**REST API 代码**

用于 HTTP DELETE 方法的 Spring REST API。

```java
@RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> updateEmployee(@PathVariable("id") int id) 
{
	System.out.println(id);
	return new ResponseEntity(HttpStatus.OK);
}

```

**REST 客户端代码**

Spring REST 客户端使用`RestTemplate`访问 HTTP DELETE api 请求。

```java
private static void deleteEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";

	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "2");

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.delete ( uri,  params );
}

```

随意复制和修改以上 Spring `RestTemplate`示例，以在您的 MVC 应用程序中构建 **Spring REST 客户端**

## 5\. 更多的`RestTemplate`示例

[Spring `RestTemplate`基本身份验证示例](https://howtodoinjava.com/spring-boot2/resttemplate-basicauth-example/)

[Spring `RestTemplate`超时配置示例](https://howtodoinjava.com/spring-boot2/resttemplate-timeout-example/)

[Spring `RestTemplateBuilder`示例](https://howtodoinjava.com/spring-restful/resttemplate-builder/)

[Spring `RestTemplate` – `HttpClient`配置示例](https://howtodoinjava.com/spring-restful/resttemplate-httpclient-java-config/)

[Spring Boot `RestTemplate` GET 示例](https://howtodoinjava.com/spring-boot2/resttemplate-get-example/)

[Spring Boot `RestTemplate` POST 示例](https://howtodoinjava.com/spring-boot2/resttemplate-post-json-example/)

[带有`RestTemplate`的 Spring Boot JUnit 示例](https://howtodoinjava.com/spring-boot2/spring-boot-junit-resttemplate/)

[带有标题示例的 Spring boot `TestRestTemplate` POST 示例](https://howtodoinjava.com/spring-boot2/testresttemplate-post-example/)

[带有`RestTemplate`的 Spring `ClientHttpRequestInterceptor`](https://howtodoinjava.com/spring-restful/clienthttprequestinterceptor/)

学习愉快！