【问题标题】:How to read HTTP 500 using a Spring RestTemplate client如何使用 Spring RestTemplate 客户端读取 HTTP 500
【发布时间】:2018-04-12 13:40:51
【问题描述】:

一个简单的 Spring Boot REST 控制器

@PostMapping(path = "check-and-submit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyOutput> checkAndSave(@RequestBody @Valid MyInput input, Errors errors){
    ResponseEntity<MyOutput> result = null;
    if (errors.hasErrors()) {
        result = new ResponseEntity<>(MyOutput.buildErrorResponse(errors), HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        myDao.save(input.buildEntity());
        result = new ResponseEntity<>(MyOutput.buildSuccessResponse(), HttpStatus.OK);      
    }
    return result;
}

以及它的测试类

public static void main(String[] args) {    
    MyInput dto = new MyInput();
    // set properties
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Content-Type", "application/json");
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    HttpEntity<MyInput> request = new HttpEntity<MyInput>(dto, headers);
    try {
        ResponseEntity<MyOutput> result = restTemplate.postForEntity(URL, request, MyOutput.class);
        System.out.println(result);
    } catch(Exception e) {
        e.printStackTrace();
    }
}

对于成功场景,这可以正常工作。但是,对于异常情况,即 HTTP 500,这会失败

org.springframework.web.client.HttpServerErrorException: 500 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)

按照其中一篇文章的建议,我创建了一个可以成功读取响应的错误处理程序

public class TestHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        Scanner scanner = new Scanner(response.getBody());
        String data = "";
        while (scanner.hasNext())
            data += scanner.next();
        System.out.println(data);
        scanner.close();
    }
}

但是即使在 HTTP 500 的情况下,我如何让 RestTemplate 读取和反序列化响应 JSON。

在任何其他人工问题标记机器人将此标记为重复之前,这里有一个关于它与其他问题有何不同的简单解释。

所有其他问题都涉及如何处理 HTTP 500,最多读取响应正文。这个问题是针对是否可以将响应反序列化为 JSON 的。这样的功能在 JBoss RESTEasy 等框架中得到了很好的建立。检查在 Spring 中如何实现相同的目标。

【问题讨论】:

  • 是的,@pvpkiran 先生,这个问题是相似的,并且受到了相同的启发,但目标不同。建议您通读完整的问题,并在发表评论之前尝试了解这与其他问题有何不同。

标签: spring-mvc spring-boot resttemplate


【解决方案1】:

这应该可以。

try {
      ResponseEntity<MyOutput> result = restTemplate.postForEntity(URL, request, MyOutput.class);
     } catch(HttpServerErrorException errorException) {
           String responseBody = errorException.getResponseBodyAsString();
           // You can use this string to create MyOutput pojo using ObjectMapper.
     }

【讨论】:

  • 是的,先生,我知道编写用于反序列化 JSON 的样板代码是一种替代方法。寻找更好的解决方案(如果有)。
猜你喜欢
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2017-01-21
相关资源
最近更新 更多