Spring RestTemplate处理自定义状态代码

时间:2017-08-23 12:30:48

标签: java spring http-headers resttemplate

我应该从我的应用程序中调用一些可以返回异常的http状态代码的服务,例如230,240等。默认错误处理程序我得到:

Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.UnknownHttpStatusCodeException: Unknown status code [230] null] with root cause...

当我使用自定义错误处理程序时,我可以避免这种情况:

@Override
    public boolean hasError(ClientHttpResponse response) throws IOException {

        int status = response.getRawStatusCode();
        if (status >= 200 && status <= 299)
            return false;

        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.is2xxSuccessful())
            return false;
        HttpStatus.Series series = statusCode.series();
        return (HttpStatus.Series.CLIENT_ERROR.equals(series)
                || HttpStatus.Series.SERVER_ERROR.equals(series));
    }

但是当RestTmplate尝试检索时,它会落入MessageBodyClientHttpResponseWrapper中的相同异常:

public boolean hasMessageBody() throws IOException {
        HttpStatus responseStatus = this.getStatusCode();
        if (responseStatus.is1xxInformational() || responseStatus == HttpStatus.NO_CONTENT ||
                responseStatus == HttpStatus.NOT_MODIFIED) {
            return false;
        }
        else if (this.getHeaders().getContentLength() == 0) {
            return false;
        }
        return true;
    }

如何正确获取响应正文?

1 个答案:

答案 0 :(得分:0)

最后,问题在Spring 5tested it解决了。