玩转Spring Boot之RestTemplate的使用

简介: 玩转Spring Boot之RestTemplate的使用

1 RestTemplate简介

在java代码里想要进行restful web client服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。Spring Boot提供了一种简单便捷的内置模板类来进行操作,这就是RestTemplate。

2 RestTemplate基本使用

2.1 依赖:

Spring Boot的web starter已经内置了RestTemplate的Bean,我们主需要将它引入到我们的Spring Context中,再进行下简单的配置就可以直接使用了。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>
复制代码

2.2 Web服务端代码:

这部分代码作为Http请求的服务端:

/**
 * @desc: HTTP服务端
 * @author: YanMingXin
 * @create: 2022/1/15-18:08
 **/
@RestController
public class RestControllerDemo {
    /**
     * 普通Get
     *
     * @param name
     * @return
     */
    @GetMapping("/get")
    private String getMethod(@RequestParam("name") String name) {
        System.out.println("getMethod : name=" + name);
        return name;
    }
    /**
     * Restful Get
     *
     * @param name
     * @return
     */
    @GetMapping("/getName/{name}")
    private String getRestName(@PathVariable("name") String name) {
        System.out.println("getRestName : name=" + name);
        return name;
    }
    /**
     * post
     *
     * @param name
     * @return
     */
    @PostMapping("/post")
    private String postMethod(@RequestParam("name") String name) {
        System.out.println("postMethod : name=" + name);
        return name;
    }
    /**
     * post json
     *
     * @param stu
     * @return
     */
    @PostMapping("/postBody")
    public String postBodyMethod(@RequestBody String stu) {
        Student student = JSONObject.parseObject(stu, Student.class);
        System.out.println("postBodyMethod : student=" + student);
        return student.toString();
    }
    /**
     * delete
     *
     * @param name
     * @return
     */
    @DeleteMapping("/delete")
    public String deleteMethod(@RequestParam("name") String name) {
        System.out.println("deleteMethod : name=" + name);
        return name;
    }
    /**
     * put
     *
     * @param name
     * @return
     */
    @PutMapping("/put")
    public String putMethod(@RequestParam("name") String name) {
        System.out.println("putMethod : name=" + name);
        return name;
    }
}
复制代码

2.3 RestTemplate代码:

配置:

/**
 * @desc: RestTemplate配置
 * @author: YanMingXin
 * @create: 2022/1/15-17:34
 **/
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(15000);
        return factory;
    }
}
复制代码

使用测试:

@SpringBootTest
class DemoApplicationTests {
    @Resource
    private RestTemplate restTemplate;
    @Test
    void getTest() {
        String str = restTemplate.getForObject("http://localhost:8888/get?name=zs", String.class);
        System.out.println(str);
    }
    @Test
    void getRestTest() {
        String name = "ls";
        String str = restTemplate.getForObject("http://localhost:8888/getName/" + name, String.class);
        System.out.println(str);
    }
    @Test
    void postTest() {
        LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.set("name", "zs");
        String str = restTemplate.postForObject("http://localhost:8888/post", map, String.class);
        System.out.println(str);
    }
    @Test
    void postBodyTest() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "zs");
        map.put("age", 23);
        String stu = JSON.toJSONString(map);
        HttpEntity<String> formEntity = new HttpEntity<String>(stu, headers);
        String str = restTemplate.postForObject("http://localhost:8888/postBody", formEntity, String.class);
        System.out.println(str);
    }
    @Test
    void putTest() {
        restTemplate.put("http://localhost:8888/put?name=zs", null);
    }
    @Test
    void deleteTest() {
        restTemplate.delete("http://localhost:8888/delete?name=zs");
    }
}
复制代码

3 其他API使用

  • exchange():在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中
    映射得到的
  • execute(): 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  • getForEntity(): 发送一个GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  • getForObject() :发送一个GET请求,返回的请求体将映射为一个对象
  • postForEntity():POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得
    到的
  • postForObject() :POST 数据到一个URL,返回根据响应体匹配形成的对象

4 注意点

  • RestTemplate需要手动的注入到我们自己的Spring Context中才能进行使用,不可以直接在一个业务类中注入使用。
  • 使用POST形式的JSON格式进行请求时,需要配置http报文的header请求头中的报文格式。


相关文章
|
2月前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
53 0
|
22天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
29 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
24天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
3月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
4月前
|
开发框架 Java .NET
SpringBoot3中的属性绑定注解和YMAL配置文件、日志
SpringBoot3中的属性绑定注解和YMAL配置文件、日志
|
4月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
6月前
|
Java 测试技术
Springboot集成JUnit5优雅进行单元测试
Springboot集成JUnit5优雅进行单元测试
|
安全 Java Maven
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
1330 1
|
10月前
|
Java Maven
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
322 0
|
10月前
|
SQL druid 前端开发
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!