spring 如何在Webclient get请求调用中传递Object列表

eqqqjvef  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(159)

如何将List对象作为参数发送到控制器
EX:

  1. @GetMapping("/demo")
  2. public List<Student> m1(List<Employee> account)
  3. {
  4. }
  5. public Employee
  6. {
  7. String id;
  8. String name;
  9. }

字符串

如何调用webclient:我试过了,

  1. Employee e = new Employee("1","tarun");
  2. Employee e1 = new Employee("2","run");
  3. List<Employee> a = new ArrayList<>();
  4. a.add(e);
  5. a.add(e1);
  6. webclient
  7. .get()
  8. .uri(x->x.path("/demo")
  9. .queryParam("account",a)
  10. .build())
  11. .accept(json)
  12. .retrieve()
  13. .bodyToMono(new parameterizedtypereference<List<Student>>(){});


当我尝试像上面得到的错误,任何人都可以请帮助我如何才能调用上面的m1方法使用webclient,我需要传递列表的m1方法.`

rta7y2nd

rta7y2nd1#

首先,确保在项目中包含SpringWebFluxWebClient的必要依赖。
如果你想使用WebClient将List对象作为参数发送给@GetMapping控制器方法,你可以使用bodyValue()
首先,Employee类应该是可序列化的

  1. public class Employee {
  2. private String id;
  3. private String name;
  4. // Constructor, getters, setters, etc.
  5. }

字符串
你的控制器方法也没有什么变化。

  1. @GetMapping("/demo")
  2. public List<Student> m1(@RequestBody List<Employee> account) {
  3. // Your implementation
  4. }


这就是你如何使用WebClient调用这个方法,

  1. import org.springframework.web.reactive.function.client.WebClient;
  2. import org.springframework.http.MediaType;
  3. // ...
  4. Employee e = new Employee("1", "tarun");
  5. Employee e1 = new Employee("2", "run");
  6. List<Employee> a = new ArrayList<>();
  7. a.add(e);
  8. a.add(e1);
  9. List<Student> result = WebClient.create()
  10. .post()
  11. .uri("/demo")
  12. .contentType(MediaType.APPLICATION_JSON)
  13. .bodyValue(a)
  14. .retrieve()
  15. .bodyToFlux(Student.class)
  16. .collectList()
  17. .block(); // block() is used here for simplicity, consider using subscribe() in a real application
  18. // 'result' now contains the response from the server

展开查看全部

相关问题