java - RestTemplate 使用 ResourceAccessException 获取正文
问题描述
我正在发送 API 并接收带有我需要解析的正文的状态代码 400
使用RestTemplate时,我无法解析响应:
try {
ResponseEntity<ResponseVO> response = restTemplate.exchange(uri, HttpMethod.POST, request, ResponseVO.class);
} catch(HttpStatusCodeException e){
// not catch
String errorpayload = e.getResponseBodyAsString();
} catch (RestClientException e) {
// catch without body
}
还建议添加错误处理程序(默认和特定),我总是得到一个ResourceAccessException
未被捕获HttpClientErrorException
且不包含正文/标题数据的
在这种情况下,我怎样才能获得正文/标题?我必须使用 RestTemplate 的替代品吗?
此外,当我在内部捕获异常时,如何返回请求上下文handleError
:
public void handleError(ClientHttpResponse response) throws IOException {
解决方案
我使用的拦截器已经读取了我的身体的问题,
将 RestTemplate 更改为使用BufferingClientHttpRequestFactory我现在可以重新读取我的正文
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
使用此包装器允许多次读取响应正文。
推荐阅读
- angular - 物料表中如何默认展开所有行?
- linux - 为什么ELF文件有这么多空格?
- sql-server - QT 连接错误 [Microsoft][ODBC SQL Server Driver][SQL Server] 用户 '' 登录失败。QODBC3: 无法连接
- iframe - 无法在超级集中显示 matomo iframe
- r - 查找属于特定 ID 的所有记录都已停用
- reactjs - 如何在 React 组件的 render() 中使用回调
- vue.js - Vue路由器不工作并且不显示任何东西
- r - 从 randomForest R 中的树中排除变量组合
- r - 以变量为矩阵元素的矩阵代数
- r - 从数字矩阵中删除 '%'