如何在Webclient获取请求调用中传递对象列表

问题描述 投票:0回答:1

如何发送List对象作为参数来获取控制器

例如:

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

}

public Employee
{
 String id;
 String name;
}

如何调用网络客户端: 我尝试过类似

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>>(){});

当我尝试像上面那样出现错误时,任何人都可以帮我如何使用 webclient 调用上述 m1 方法,我需要传递 m1 方法的列表。`

java spring spring-boot spring-mvc java-8
1个回答
0
投票

首先,确保在项目中包含 Spring WebFluxWebClient 必要的依赖项。

如果您想使用 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
© www.soinside.com 2019 - 2024. All rights reserved.