Smith
Smith

Reputation: 151

Unable to send message as a String using Spring reactive - Webclient

I am unable to send String message to rest service using Spring-webflux Webclient. Below are the code snippet :

public WebClient getWebClient(String baseUrl)
    {
        HttpClient httpClient = HttpClient.create()
                .tcpConfiguration(client ->
                        client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .doOnConnected(conn -> conn
                                .addHandlerLast(new ReadTimeoutHandler(10))
                                .addHandlerLast(new WriteTimeoutHandler(10))));
         
        ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);     
     
        return WebClient.builder()
                .baseUrl(baseUrl)
                .clientConnector(connector)
                //.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

Using above method to hit service and subscribe to response :-

Mono<String> response = getWebClient(someBaseUrl).post()
                .uri(postUri) //post mapping URI
                .contentType(MediaType.TEXT_HTML)
                .body(Mono.just(payload), String.class) //message to be sent
                .retrieve()
                .bodyToMono(String.class); //type of response to receive

The below subscribe able to print Success

response.subscribe(
                value -> log.info("Response from Web service : "+value), 
                error -> log.error("Response from Web Service : "+error.getMessage()) 
                );

Service Side controller :

@PostMapping("/test")
    public String test(String message) {
        System.out.println("Received message : "+message);
        return "Success";
    }

Above code prints null but it's able to send response success to caller. Kindly help.

Upvotes: 0

Views: 611

Answers (1)

Domenico Sibilio
Domenico Sibilio

Reputation: 1387

You should annotate String message with @RequestBody.

E.g.:

@PostMapping("/test")
public String test(@RequestBody String message) {
  System.out.println("Received message : "+message);
  return "Success";
}

Upvotes: 1

Related Questions