gpt4 book ai didi

java - ResponseEntityExceptionHandler 为 401 异常返回空响应主体

转载 作者:行者123 更新时间:2023-11-29 04:11:14 28 4
gpt4 key购买 nike

我正在尝试使用 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();
}

目前我的 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);
}

但是,仅对于 HttpStatus 401 异常,我得到一个空的响应主体。

日志示例:

400| {"error_description":"Bad client credentials","error":"invalid_client"}

401| Bad authentication response body | Response Body |

有谁知道如何获取 401 异常的响应正文?

编辑:当使用 Postman 调用身份验证服务器时,我得到非空 401 responseBody:

{
"error": "invalid_token",
"error_description": "Token was not recognised"
}

最佳答案

我终于能够记录 401 异常的响应正文。我添加了依赖

org.apache.httpcomponents:httpclient

并配置了 Rest 模板请求工厂

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

显然,默认请求工厂 SimpleClientHttpRequestFactory 无法读取 401 Http Status 的响应主体。

关于java - ResponseEntityExceptionHandler 为 401 异常返回空响应主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54932011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com