Reputation: 61
I am getting 400 bad request when I access form data through @RequestParam
My Java code
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);
}
Controller 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;
}
How to access form data in controller?
Upvotes: 1
Views: 7062
Reputation: 3457
You need to use 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");
});
}
Upvotes: 6
Reputation: 31
Your postWithFormData() code is OK.
The problem is in your rest4(..) method. You can't use @RequestParam annotation in order to get POST parameter (it should be used to get GET parameters).
You can use DTO instead. If you change the code this way it should work:
@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;
}
}
Upvotes: 1