Reputation: 3446
Following the Spring WebClient tutorial here I'm trying to pass username and password in the request body (no basic auth) to the API endpoint as it expects these as parameters.
I've tested in Postman supplying the username and password as separate fields in the body and setting the contentType as application/x-www-form-urlencoded. This results in getting the expected token, however when I print out the response below using my implementation using WebClient, it prints:
{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}
|
TcpClient tcpClient = TcpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECTION_TIMEOUT_MILIS)
.doOnConnected(connection -> {
connection.addHandlerLast(new ReadTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
connection.addHandlerLast(new WriteTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
});
WebClient client = WebClient.builder().baseUrl(BASE_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))).build();
LinkedMultiValueMap<String, String> multiMap = new LinkedMultiValueMap<>();
multiMap.add("username", username);
multiMap.add("password", password);
BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter = BodyInserters.fromMultipartData(multiMap);
WebClient.RequestHeadersSpec<?> request = client.post().uri(API_CALL_GET_TOKEN).body(inserter);
String response = request.exchange().block().bodyToMono(String.class).block();
System.out.println(response);
Upvotes: 1
Views: 3208
Reputation: 3446
Providing .accept(MediaType.APPLICATION_JSON)
provided the response:
WebClient client = WebClient.create();
LinkedMultiValueMap<String, String> credentials = new LinkedMultiValueMap<>();
credentials.add("username", username);
credentials.add("password", password);
String response = client.post()
.uri(BASE_URL + API_CALL_GET_TOKEN)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromFormData(credentials))
.retrieve()
.bodyToMono(String.class)
.block();
return response;
Upvotes: 1