The*_*iff 4 java spring resttemplate
我正在尝试使用 RestTemplate 实现对身份验证服务器的 Rest 调用,并在服务器返回异常的情况下记录响应。为了做到这一点,我使用了 ResponseEntityExceptionHandler 来处理 HttpClientErrorException 和 HttpServerErrorException。
public Response sendRequest(Request requestBody, String url, HttpMethod httpMethod, Response responseBody) {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody.getBody(),
this.securityHeaders);
ResponseEntity<? extends Response> response = restTemplate.exchange(url, httpMethod, request,
responseBody.getClass());
return response.getBody();
}
Run Code Online (Sandbox Code Playgroud)
目前我的 ResponseEntityExceptionHandler 如下
@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {
private static Logger log = LoggerFactory.getLogger(RestResponseExceptionHandler.class);
private HttpHeaders headers = new HttpHeaders();
@ExceptionHandler(value = { HttpClientErrorException.class, HttpServerErrorException.class })
protected ResponseEntity<Object> handleConflict(HttpStatusCodeException ex, WebRequest request) {
ErrorMessage responseBody = new ErrorMessage();
try {
JSONObject bodyOfException = new JSONObject(ex.getResponseBodyAsString());
log.warn("{}| {}", ex.getStatusCode(), bodyOfException);
responseBody.setErrorAndDescription(bodyOfException.optString("error"),
bodyOfException.optString("error_description"));
} catch (JSONException e) {
log.error("{}| Bad authentication response body | Response Body | {}", ex.getStatusCode(),
ex.getResponseBodyAsString());
}
return handleExceptionInternal(ex, responseBody, headers, ex.getStatusCode(), request);
}
Run Code Online (Sandbox Code Playgroud)
}
但是,仅对于 HttpStatus 401 异常,我得到一个空的响应正文。
日志示例:
400| {"error_description":"Bad client credentials","error":"invalid_client"}
401| Bad authentication response body | Response Body |
Run Code Online (Sandbox Code Playgroud)
有谁知道我如何获得 401 异常的响应正文?
编辑:当使用邮递员调用身份验证服务器时,我得到非空 401 responseBody:
{
"error": "invalid_token",
"error_description": "Token was not recognised"
}
Run Code Online (Sandbox Code Playgroud)
The*_*iff 12
我终于能够记录 401 异常的响应正文。我添加了依赖项
org.apache.httpcomponents:httpclient
并配置了 Rest 模板请求工厂
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
Run Code Online (Sandbox Code Playgroud)
显然,默认请求工厂 SimpleClientHttpRequestFactory 无法读取 401 Http 状态的响应正文。
| 归档时间: |
|
| 查看次数: |
2353 次 |
| 最近记录: |