I have a springboot project which uses Springboot Resttemplate. We have moved to springboot 2.0.1 from 1.5.3 and we are trying to make the rest calls from it asynchronous by us
The first step is to build WebClient
object with the baseUrl;
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080/api") //baseUrl
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
Then choose the method and append the path along with the request variables or body payload.
ResponseSpec responseSpec = webClient
.get()
.uri(uriBuilder -> uriBuilder.path("/findById") //additional path
.queryParam("id", id).build())
.retrieve()
.onStatus(HttpStatus::is4xxClientError, response -> Mono.error(new CustomRuntimeException("Error")));
Wait for the response with block()
function of bodyToMono
. If you want response as String, you can convert it using google's gson library.
Object response = responseSpec.bodyToMono(Object.class).block();
Gson gson = new Gson();
String str = gson.toJson(response);
If you don't want to need to know the status of the api call, you can do like following.
webClient
.post()
.uri(uri -> uri.path("/save").build())
.body( BodyInserters.fromObject(payload) )
.exchange().subscribe();