【问题标题】:Response Entity is null despite Error-404 JSON returned by a server尽管服务器返回了 Error-404 JSON,但响应实体为空
【发布时间】:2016-05-02 14:08:14
【问题描述】:

我正在使用 Spring REST 来处理我的请求。 这是我的代码示例:

RestTemplate restTemplate = new RestTemplate();
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(apiAddress + "action?uniqueId=" + id, HttpMethod.GET, entity, String.class);

        }catch (RestClientException ex) {
            System.out.println(responseEntity.toString());
            String errorMessage = ex.getMessage();
        }

当我获得 200 个状态和带有返回值的 JSON 时,一切正常。 例如,问题在于 404 JSON。 在调试过程中,我发现当 404 发生时,我的 responseEntity 仍然为空,因此我无法获取错误代码。此外,我无法从我知道它正在发送的服务器获得 JSON 回复。

我尝试了 HTTP 请求器,它可以很好地处理 200 个响应 - 给我请求的数据和 404 个响应 - 给我一个带有错误描述的 JSON。

最好的问候, 卡罗尔

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    我已经设法弄清楚发生了什么。 我希望它可以帮助别人:

    我已经实现了ResponseErrorHandler

    public class VariousErrorsResponseHandler implements ResponseErrorHandler {
    @Override
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        if(clientHttpResponse.getStatusCode() == HttpStatus.NOT_FOUND || clientHttpResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) return false;
        else return true;
    }
    
    @Override
    public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
        System.err.println(clientHttpResponse.getStatusCode() + "\n" + clientHttpResponse.getStatusText());
    }
    }
    

    然后将其设置为restTemplate的错误处理程序:

    restTemplate.setErrorHandler(new VariousErrorsResponseHandler());
    

    完成了:)

    【讨论】:

      猜你喜欢
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2017-10-08
      • 1970-01-01
      • 2020-04-30
      相关资源
      最近更新 更多