无法在webflux / webclient中访问表单数据

时间:2019-03-24 10:31:32

标签: spring-webflux

通过@RequestParam访问表单数据时,我收到400个错误的请求

我的Java代码

public Flux<String> postWithFormData() {

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("id", "Test Post Form data");

    return webClient
            .post()
            .uri("http://localhost:8080/webclient/rest6")
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            //.syncBody(map)
            .body(BodyInserters.fromFormData("id", "Test Post Form data"))
            .retrieve()
            .bodyToFlux(String.class);

}

控制器类

@RequestMapping(value = "rest4", method = RequestMethod.POST)
public ResponseEntity<String> rest4(@RequestParam("id") String id) {
    ResponseEntity<String> response = new ResponseEntity<String>("Success",HttpStatus.OK);
    return response;

}

如何在控制器中访问表单数据?

2 个答案:

答案 0 :(得分:0)

您的 postWithFormData()代码正常。

问题出在您的 rest4(..)方法中。您不能使用 @RequestParam 注释来获取POST参数(应该使用它来获取GET参数)。

您可以改用DTO。如果您以这种方式更改代码,它将可以正常工作:

  @PostMapping(value = "rest4")
  public ResponseEntity<String> rest4(ValueDto value) {
    System.out.println(value.getId());
    ResponseEntity<String> response = new ResponseEntity<String>("Success", HttpStatus.OK);
    return response;
  }

  static class ValueDto {
    private String id;

    public String getId() {
      return id;
    }

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

答案 1 :(得分:0)

您需要使用ServerWebExchange。

@PostMapping(value = "webclient/rest6", consumes = {"application/x-www-form-urlencoded"})
public Mono<String> redirectComplete(ServerWebExchange exchange) {
    Mono<MultiValueMap<String, String>> data = exchange.getFormData();

    return data.map(formData -> {
        String parameterValue = formData.getFirst("id");
        ...
        return Mono.just("result data");
    });
}