【问题标题】:Get the customized Response JSON from 422 Unprocessable Entity从 422 Unprocessable Entity 获取自定义的响应 JSON
【发布时间】:2022-01-27 14:50:22
【问题描述】:

我有一个调用第三方 API 的 Java Springboot 微服务。对于我的一个测试用例,API 返回 422 Unprocessable entity with a custom Response JSON Body

{
    "request_status": "error",
    "status": "error",
    "requested_url": "www.example.de",
    "url": "http://www.newexample.de/",
    "issue": "redirect",
    "recommendedUrl": true,
    "error_message": "The web address you entered redirects to another website."
}

我无法在我的微服务中检索此响应正文。我的代码如下所示

try {
    HttpEntity<Input_Class> httpentity = new HttpEntity<Input_Class>(                      inputClassObj, headers);
    responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpentity,
         new ParameterizedTypeReference<Output_Class>() {});

} catch(RestClientException ue) {
     if (ue instanceof HttpStatusCodeException) {
         String errorResponse = ((HttpStatusCodeException) ue).getResponseBodyAsString();
         logger.info(errorResponse);
}

我在日志中看到的errorResponse是

{
    "status": "ERROR",
    "errorMessage": "Unprocessable Entity"
}

谁能告诉我应该使用哪个异常类来获取 API 发送的响应正文。

【问题讨论】:

标签: java spring-boot rest maven


【解决方案1】:
    catch(RestClientException ue) {
     if (ue instanceof HttpStatusCodeException) {
         String errorResponse = ((HttpStatusCodeException) ue).getResponseBodyAsString();
         logger.info(errorResponse);
}

这个代码块确实有效。 errorResponse 返回响应 JSON。我正在使用另一个端点 url 来包装响应,因此没有得到实际响应。

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2022-09-30
    相关资源
    最近更新 更多