服务器响应为HTTP 400错误请求,其中包含详细信息,但仅客户端日志:
java.io.IOException: Server returned HTTP response code: 400 for URL:
http://localhost:7101/test?param=1
我想记录有关我可以从HttpClientErrorException获取的错误的详细信息:
httpEx.getCause();
httpEx.getResponseBodyAsString();
httpEx.getResponseHeaders();
httpEx.getStatusCode();
httpEx.getStatusText()
我也设置了处理程序,但是它仅捕获正HTTP编码,例如HTTP 200。 在其他情况下,它无法处理错误。
Java 1.7 春天3.2.18
代码:
restTemplate is class org.springframework.web.client.RestTemplate
[...]
try {
HttpEntity request = new HttpEntity(createHeaders(userName, userPassword));
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity<ResponseMessage> response =
restTemplate.exchange(resource,
HttpMethod.GET,
request,
ResponseMessage.class);
ResponsePaymentsMessage obj = response.getBody();
} catch (HttpClientErrorException httpEx) {
if (httpEx.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
throw new NotFoundException("Not found exception " + resource);
}
[...]
}
错误处理程序类:
public class MyResponseErrorHandler implements ResponseErrorHandler {
private static final Logger LOG = LoggingUtilsSlf.getInvokingClassSLFLogger();
@Override
public void handleError(ClientHttpResponse clienthttpresponse) throws IOException {
if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) {
LOG.debug(HttpStatus.FORBIDDEN + " response. Throwing authentication exception");
throw new IOException();
}
}
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
if (clientHttpResponse.getStatusCode() != HttpStatus.OK) {
LOG.debug("Status code: " + clientHttpResponse.getStatusCode());
LOG.debug("Response" + clientHttpResponse.getStatusText());
LOG.debug(clientHttpResponse.getBody().toString());
if (clientHttpResponse.getStatusCode() == HttpStatus.FORBIDDEN) {
LOG.debug("Call returned a error 403 forbidden respone");
return true;
}
}
return false;
}
}
somone可以帮助您从restTemplate.exchange捕获HTTP响应的详细信息吗?