javaspringhttpresttemplate

Cannot parse the response of restTemplate.exchange


I have the following code to submit a post http call:

HttpHeaders headers = new HttpHeaders();
headers.set(TENANT_ID_HEADER, event.getTenantId());
HttpEntity<InputObj> requestEntity = new HttpEntity<>(inputObj, headers);
ResponseEntity<Object> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Object.class
            );

The call is successfully reaching the server and it returns a 200 success code

ResponseEntity.ok().body("Successfully handled the request");

I keep getting the following error after the call is done

Exception while performing API call with message : Error while extracting response for type [class java.lang.Object] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Successfully': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Successfully': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

I tried using RestTemplate with converters instead of the default one in org.springframework.web.client.
However, I still get the same error


Solution

  • A better idea would be to deserialize the response to String instead of Object as the response type.

    Created a small demo.

    Controller:

    @RestController
    @RequestMapping("demo")
    public class DemoController {
        @PostMapping
        public ResponseEntity<String> demo() {
            return ResponseEntity.ok().body("Successfully handled the request");
        }
    }
    

    Main logic with RestTemplate:

    public class Demo {
        public static void main(String[] args) {
            var restTemplate = new RestTemplate();
            var response = restTemplate.exchange(
                    "http://localhost:8081/demo",
                    HttpMethod.POST,
                    null,
                    String.class
            );
    
            System.out.printf("Response Code: %s%n", response.getStatusCode());
            System.out.printf("Response Body: %s%n", response.getBody());
        }
    }
    

    Output:

    Response Code: 200 OK
    Response Body: Successfully handled the request