ramostear.comramostear.com 谭朝红的技术分享博客

格言 编程是一门技术,也是一门艺术 !

使用RestTemplate对Restful服务进行调用

使用RestTemplate对Restful服务进行调用

Spring Boot(十)— RestTemplate

Spring Boot提供的RestTemplate类可以在应用中调用Restful Web服务,这极大的简化了与Http服务的通信方式,统一了Restful服务调用的标准,其内部对Http进行了封装,我们只需要传递相应的URL、请求方法、主体信息以及返回值类型即可,相比于HttpClient,RestTemplate以一种更优雅的方式对Restful Web服务进行调用。下面是的代码展示了如何使用@Bean注解创建RestTemplate并进行连接。

package com.ramostear.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

接下来,我将演示不同请求方法下如何使用RestTemplate。在开始正文之前,我们需要创建一个提供Restful Web Service的控制器,下面给出的代码显示了控制器的详细内容:

package com.ramostear.application.controller;

import com.ramostear.application.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }

    @GetMapping("/users")
    public ResponseEntity<Object> getUser(){
        return new ResponseEntity<>(userRepository.values(), HttpStatus.OK);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user){
        userRepository.put(user.getId(),user);
        return new ResponseEntity<>("User is created successfully",HttpStatus.CREATED);
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<Object> updateUser(@PathVariable(name = "id") long id,@RequestBody User user){
        userRepository.remove(id);
        user.setId(id);
        userRepository.put(id,user);
        return new ResponseEntity<>("User is updated successfully",HttpStatus.OK);
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<Object> delete(@PathVariable(name = "id") long id){
        userRepository.remove(id);
        return new ResponseEntity<>("User is deleted successfully",HttpStatus.OK);
    }

}

除此之外,还需要创建一个数据模型作为用户信息的载体,下面的代码给出了用户数据模型的详细信息:

package com.ramostear.application.model;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:12
 * @modify by :
 * @since:
 */
@Getter
@Setter
@NoArgsConstructor
public class User {
    private long id;
    private String name;

    public User setId(long id){
        this.id = id;
        return this;
    }

    public User setName(String name){
        this.name = name;
        return this;
    }
}

1. HTTP GET请求

现在,我们可以使用RestTemplate的exchange()方法来请求URL为http://localhost:8080/usersGET API。下面将给出RestTemplate调用Restful Web服务的基本流程:

  • 创建RestTemplate对象,这里使用@AutoWired注解进行自动装配
  • 使用HttpHeaders对象设置请求头参数
  • 使用HttpEntity包装类对请求对象进行包装
  • 调用exchange()方法,并传入URL、HttpMethod以及返回值类型

下面的代码显示了使用RestTemplate的exchange()方法调用Restful Web服务的详细过程:

@RestController
public class UserWebService {

    @Autowired
    RestTemplate restTemplate;

    private static final String ROOT_URI = "http://localhost:8080/users";

    @GetMapping("/rest/template/users")
    public String getUsers(){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(ROOT_URI, HttpMethod.GET,entity,String.class).getBody();
    }
}

2. HTTP POST请求

RestTemplate调用POST API的流程与调用GET API的流程基本相同,现在,我们使用RestTemplate调用POST API创建一个新的用户。相比调用GET API,唯一不同的地方在于需要把用户信息包装到请求主体中,同时需要将请求方法修改为POST。下面的代码展示了如何调用POST API:

@RestController
public class UserWebService {

    @Autowired
    RestTemplate restTemplate;

    private static final String ROOT_URI = "http://localhost:8080/users";

    @PostMapping("/rest/template/users")
    public String createdUser(@RequestBody User user){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(user,headers);
        return restTemplate.exchange(ROOT_URI,HttpMethod.POST,entity,String.class).getBody();
    }
}

3. HTTP PUT 请求

接下来,使用RestTemplate调用PUT API对用户信息进行修改,与调用POST API的方法相同,我们需要将待修改的用户信息包装到请求主体中,同时需要修改请求方法为PUT。下面代码展示了如何调用PUT API:

@RestController
public class UserWebService {

    @Autowired
    RestTemplate restTemplate;

    private static final String ROOT_URI = "http://localhost:8080/users";

   @PutMapping("/rest/template/users/{id}")
    public String updateUser(@PathVariable(name = "id")long id,@RequestBody User user){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(user,headers);
        return restTemplate.exchange(ROOT_URI+"/"+id,HttpMethod.PUT,entity,String.class).getBody();
    }
}

4. HTTP DELETE请求

RestTemplate调用DELETE API的方法与上述三种请求方法基本一致,需要注意的是HttpMethod的设置,需要设置为DELETE。下面的代码展示了如何调用DELETE API删除用户信息:

@RestController
public class UserWebService {

    @Autowired
    RestTemplate restTemplate;

    private static final String ROOT_URI = "http://localhost:8080/users";

   @DeleteMapping("/rest/template/users/{id}")
    public String deleteUser(@PathVariable(name = "id")long id){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(ROOT_URI+"/"+id,HttpMethod.DELETE,entity,String.class).getBody();
    }
}

5. 代码清单

下面给出的是完整的RestTemplate调用Restful Web服务的代码:

package com.ramostear.application.webservice;

import com.ramostear.application.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author ramostear
 * @create-time 2019/3/8 0008-0:36
 * @modify by :
 * @since:
 */
@RestController
public class UserWebService {

    @Autowired
    RestTemplate restTemplate;

    private static final String ROOT_URI = "http://localhost:8080/users";

    @GetMapping("/rest/template/users")
    public String getUsers(){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(ROOT_URI, HttpMethod.GET,entity,String.class).getBody();
    }

    @PostMapping("/rest/template/users")
    public String createdUser(@RequestBody User user){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(user,headers);
        return restTemplate.exchange(ROOT_URI,HttpMethod.POST,entity,String.class).getBody();
    }

    @PutMapping("/rest/template/users/{id}")
    public String updateUser(@PathVariable(name = "id")long id,@RequestBody User user){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(user,headers);
        return restTemplate.exchange(ROOT_URI+"/"+id,HttpMethod.PUT,entity,String.class).getBody();
    }

    @DeleteMapping("/rest/template/users/{id}")
    public String deleteUser(@PathVariable(name = "id")long id){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<User> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(ROOT_URI+"/"+id,HttpMethod.DELETE,entity,String.class).getBody();
    }
}

Maven build 文件 — pom.xml:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ramostear</groupId>
    <artifactId>rest-template</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rest-template</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

应用程序主文件 — RestTemplateApplication.java:

package com.ramostear.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

6. 打包运行

现在,可以使用下面的命令创建一个可执行的jar文件,并运行该jar文件。

使用maven命令创建可执行的jar文件:

mvn clean install

执行此命令,当控制台窗口显示“BUILD SUCCESS”信息后,你可以在当前工程目下的target子目录中找到创建的JAR文件。

接下来,使用以下命令运行创建的JAR文件:

java -jar JARFILE

执行命令,并观察控制台窗口输出的日志信息。

7. 测试

启动Postman应用程序,在地址栏中输入以下的URL,并观察测试结果。

7.1 通过RestTemplate获取用户信息

请求URL:http://localhost:8080/rest/template/users

请求方法:GET

参数:无

7.2 通过RestTemplate新增用户

请求URL: http://localhost:8080/rest/template/users

请求方法:POST

参数:{“id”:3,”name”:ramostear}

7.3 通过RestTemplate更新用户

请求URL: http://localhost:8080/rest/template/users/3

请求方法:PUT

参数:{“id”:3,”name”:”reader”}

7.4 通过RestTemplate删除用户

请求URL: http://localhost:8080/rest/template/users/3

请求方法:DELETE

参数:无