I am using the new Spring 5 WebClient to retrieve the JSON response from the JSON Placeholder tester website (https://jsonplaceholder.typicode.com/) using a POST request sent to the URI https://jsonplaceholder.typicode.com/posts placed in my request body as follows:
{
title: 'foo',
body: 'bar',
userId: 1
}
My code is as follows:
/*
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
String myTestData = "{\r\n" +
" \"title\": \"foo\",\r\n" +
" \"body\": \"bar\",\r\n" +
" \"userId\": 1\r\n" +
"}";
try {
//RestTemplate approach
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "https://jsonplaceholder.typicode.com/posts";
HttpEntity<String> request0 = new HttpEntity<>(new String(myTestData));
String foo = restTemplate.postForObject(fooResourceUrl, request0, String.class);
//WebClient approach
WebClient client = WebClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
. build();
UriSpec<RequestBodySpec> uriSpec = client.method(HttpMethod.POST);
RequestBodySpec bodySpec = uriSpec.uri("/posts");
RequestHeadersSpec<?> headersSpec = bodySpec.bodyValue(myTestData);
Mono<String> response4 = headersSpec.retrieve().bodyToMono(String.class);
String myResponseString = response4.block();
log.debug("WebClient responseMono<String> response4.block() - myResponseString : " + myResponseString);
} catch (Exception e) {
log.debug("Exception : {}", e.toString(), e);
}
However, I am getting a WebClientRequestException > UnknownHostException with the detailed message : failed to resolve 'jsonplaceholder.typicode.com' after 2 queries.
I can't see why WebClient is unable to connect to the jsonplaceholder website URI. I am running inside a NetFlix Eureka Discovery environment with several API REST services registered with Eureka including this one. Please help.