0

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.

Ezani
  • 535
  • 3
  • 18
  • Do you get different response codes for other URLs? If not, it might be a missing proxy config in your WebClient. – Elmar Brauch Jul 03 '22 at 06:00
  • Yes I get a different response for another URL which I have tested working with Swagger-UI also (together with this one). That URL was giving SSL handshaking error. I am wondering if the Eureka environment is causing the problem as my WebClient code is very straightforward - just to connect to the JSON placeholder fake data URL with a POST request and the standard request body. I will try the RestTemplate now to see if that works. – Ezani Jul 03 '22 at 12:00
  • I have just tried accessing the same URL (placeholder.typicode.com) using the RestTemplate and it is giving the same unable to access URL error as follows leading to my believing it could be a Eureka Discovery issue. This is the exception I got : ResourceAccessException. Cause : UnknownHostException. Detailed error message: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://jsonplaceholder.typicode.com/posts": jsonplaceholder.typicode.com; nested exception is java.net.UnknownHostException: jsonplaceholder.typicode.com – Ezani Jul 03 '22 at 12:16

1 Answers1

0

Not sure why you are getting your errors, but your error message

"failed to resolve 'jsonplaceholder.typicode.com' after 2 queries."

may suggest that you are hitting your server more often than allowed? I don't see a problem with your code. However, when I tried to send similar request with different very simplistic Http client it worked. Here is my code:

public static void externalHttpTest() {
    HttpClient client = new HttpClient();
    try {
        client.setContentType("application/json; charset=UTF-8");
        client.setConnectionUrl("https://jsonplaceholder.typicode.com/posts");
        String myTestData = "{\"title\": \"foo\",\"body\": \"bar\",\"userId\": 1}";
        ByteBuffer bb = ByteBuffer.wrap(myTestData.getBytes(StandardCharsets.UTF_8));
        String result = client.sendHttpRequest(HttpClient.HttpMethod.POST, bb);
        System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage() + " " + result);
    } catch (IOException ioe) {
        System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage());
        ioe.printStackTrace();
    }
}

And the output I recieved is:

201 Created {  "title": "foo",  "body": "bar",  "userId": 1,  "id": 101}

The class HttpClient is part of Open-source library written and maintained by me. Here is the Javadoc for HttpClient class. The library is called MgntUtils and can be found as Maven artifact here or on the Github with source code and Javadoc here
I also hit this URL with Advanced Rest Client (Chrome plugin similar to Postman) and it worked as well

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • Michael, thanks for your help. Could you perhaps do the same using RestTemplate and the newer WebClient and see whether you're hitting the same problem as me? Thks. – Ezani Jul 04 '22 at 03:34
  • Michael, for the ByteBuffer used in your code, is your dependency antlr, lowagie or from java.nio ? Thks, need to know the right import statement to use. – Ezani Jul 04 '22 at 03:48
  • Michael, okay I tested with your code and your HttpClient and still getting the UnknownHostException so I believe its nothing to do with the WebClient or RestTemplate...its some sort of blocking issue. Need to check my firewall and other URI blocking possibilities... – Ezani Jul 04 '22 at 03:53
  • I guess you figured out the dependency was java.nio. I agree since you are getting the same error from different clients your problem is not related to any particular client – Michael Gantman Jul 04 '22 at 09:05