RestTemplate exchange

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1AN411Z7mx?p=12

当请求的控制器返回值类型为 List<xx>、Set<xxx> 等带有泛型类型的类型时,就不能使用 getForObject、getForEntity、postForObject 等,因为它们都是只能设置返回值类型,而不能设置类型的泛型。

这时就需要用到 exchange 方法。

除此之外,如果需要设置请求头参数情况也需要使用 exchange 方法。

Application Service 中

新增 POJO People.java

package io.github.jihch.pojo;

public class People {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public People() {
    }

    public People(int id, String name) {
        this.id = id;
        this.name = name;
    }
}


DemoController.java 中新增方法

import io.github.jihch.pojo.People;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class DemoController {

    @RequestMapping("/demo5")
    public People demo5() {
        return new People(1, "jihch");
    }

    @RequestMapping("/demo6")
    public List<People> demo6() {
        List<People> list = new ArrayList<>();
        list.add(new People(1, "jihch1"));
        list.add(new People(2, "jihch2"));
        return list;
    }

}

Application Client 中的单元测试

import io.github.jihch.pojo.People;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class ClientApplicationTests {

    @Test
    void withObject() {
        RestTemplate restTemplate = new RestTemplate();
        People people = restTemplate.getForObject("http://localhost:8080/demo5", People.class);
        System.out.println(people);
        System.out.println(people.getId());
        System.out.println(people.getName());
    }

}
People{id=1, name='jihch'}
1
jihch