【发布时间】:2017-08-23 12:30:47
【问题描述】:
我应该从我的应用程序中调用一些可以返回异常 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;
}
如何正确获取响应正文?
【问题讨论】:
-
Spring 的
HttpStatus是一个枚举,不支持未分配的 HTML 代码。基本上,您有两个选择: 1. 在处理这些响应的路径上覆盖所有有问题的代码(使用您自己的不调用该枚举的实现,仅使用原始状态代码); 2. 向 Spring 团队请求增强(可能有already be one)。
标签: java spring http-headers resttemplate