Robin Elvin
Robin Elvin

Reputation: 1255

How to handle various responses with Jackson ObjectMapper and Spring's RestTemplate?

I am consuming a REST service with Spring's RestTemplate and the Jackson ObjectMapper. The problem is if there is an error then the JSON that gets returned is nothing like the object I expect and so it fails. Additionally I cannot even use String.class as this throws a similar error. I don't even know what the response looks like because the exception is thrown on the actual request and so I never get the response to be able to inspect.

Here's some code:

    String url = BASE_URL + USER_LOGIN_URL;

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> postData = new LinkedMultiValueMap<String, String>();
    // Postdata added here

    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(postData, headers);

        UserInfo userInfo = restTemplate.postForObject(url, entity, UserInfo.class); // Doesn't work if not UserInfo

        // ** OR THE FOLLOWING **


        String response = restTemplate.postForObject(url, entity, String.class);
        logger.debug(response); // Never reaches here because ObjectMapper seems to expect a JSON object named "String"
        UserInfo userInfo = objectMapper.readValue(response, UserInfo.class);

Upvotes: 1

Views: 1142

Answers (1)

Sanjay
Sanjay

Reputation: 8955

I think RestTemplate uses a DefaultResponseErrorHandler for handling error responses (code beginning with 4 or 5). That throws an instance of HttpStatusCodeException with a method getResponseBodyAsString().

So, you can catch that exception and extract the response as a String.

Upvotes: 1

Related Questions