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

eqqqjvef  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(66)

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

@GetMapping("/demo")
public List<Student> m1(List<Employee> account)
{

}

public Employee
{
 String id;
 String name;
}

字符串

如何调用webclient:我试过了,

Employee e = new Employee("1","tarun");
Employee e1 = new Employee("2","run");
List<Employee> a = new ArrayList<>();
a.add(e);
a.add(e1);
webclient
.get()
.uri(x->x.path("/demo")
.queryParam("account",a)
.build())
.accept(json)
.retrieve()
.bodyToMono(new parameterizedtypereference<List<Student>>(){});


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

rta7y2nd

rta7y2nd1#

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

public class Employee {
    private String id;
    private String name;

    // Constructor, getters, setters, etc.
}

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

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


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

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.MediaType;

// ...

Employee e = new Employee("1", "tarun");
Employee e1 = new Employee("2", "run");
List<Employee> a = new ArrayList<>();
a.add(e);
a.add(e1);

List<Student> result = WebClient.create()
        .post()
        .uri("/demo")
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(a)
        .retrieve()
        .bodyToFlux(Student.class)
        .collectList()
        .block(); // block() is used here for simplicity, consider using subscribe() in a real application

// 'result' now contains the response from the server

相关问题