简体   繁体   中英

Spring rest template garbage error response body

I have the following rest template config:

@Bean
public RestTemplate restTemplate() {
    RestTemplate template = new RestTemplate();
    template.getMessageConverters().add(new ObjectToUrlEncodedConverter());
    return template;
}

ObjectToUrlEncodedConverter is copied as is from this answer

And I call the rest API as mentioned below:

try {
        response = template.exchange(uri, httpRequestObject.getMethod(), requestEntity, httpRequestObject.getResponseClass());
        responseObject.setHeaders(response.getHeaders().toSingleValueMap());
        responseObject.setHttpStatus(response.getStatusCode());
        responseObject.setResponseBody(response.getBody());
    } catch (HttpStatusCodeException ex) {
        log.error("Non OK response received from server. Status code: {}, response: {}", ex.getStatusCode(), ex.getResponseBodyAsString());
        throw ex;
    }

The problem I am facing is, when the response is 4xx or 5xx series, The response body ex.getResponseBodyAsString() is giving garbage values. Something like this: 0E%ܙ6 1 Y hP N \\]8 w +Q \\ :S Ȕ 뚈M 'Z ml ) @ ]B͎ L؏4Ğ V ` V Qx F<{Q /fZ S 3RNy >ć ]S +Е= ! x9 )Ԏ n%

I have tried setting the Charset to "UTF-8" while getting the errorResponseBody like the following.

ex.getResponseBodyAsString(Charset.forName("UTF-8"))

also, building the string from responseBodyByteArray as follows:

new String(ex.getResponseBodyAsByteArray())

But still no luck.

The same endpoint works well in Postman. Rest template seems to be messing up the error response body somehow.

I am not sure what the problem was exactly. I configured the rest template to use apache Http client instead of the default HttpUrlConnection used by rest template.

This seemed to work well and fixed the garbage error response body issue.

This tutorial helps us do the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM