【问题标题】:java.lang.UnsupportedOperationException:null when setting header using response entity in springjava.lang.UnsupportedOperationException:在spring中使用响应实体设置标头时为null
【发布时间】:2019-05-12 07:26:48
【问题描述】:

我正在调用一个 Web 服务,它返回给我 ResponseEntity 对象。现在我在从 ResponseEntity 获取 HttpHeaders 信息后设置位置标头。

responseEntity.getHeaders().setLocation(uriBuilder.path("/empl/{id}").buildAndExpand(empl.getEmpId()).toUri());

上面的代码行抛出 java.lang.UnsupportedOperationException 因为 headers 是不可修改的。在这种特殊情况下如何设置位置标头?

【问题讨论】:

  • 确保 empl.getEmpId() 返回非空值。
  • 如果您从responseEntity 获得标题似乎是不可变的,请查看stackoverflow.com/a/41482673
  • @Alien 是的,它返回非空值。正如 Kruschenstein 所提到的,从 responseEntity 返回的标头是不可修改的,因为它是不可变的
  • @Kruschenstein 感谢您的评论。我认为在从 responseEntity 中提取标头信息后可以采取一种方法。您提到的链接中的解决方案是我所做的,在返回 responseEntity 之前设置标题信息

标签: spring spring-boot spring-mvc


【解决方案1】:

这是我建议使用的:

@GetMapping(value = "/get-products-detail/", produces = "application/json; charset=UTF-8")
    public ResponseEntity<Object> getProductsDetail(@RequestParam Long userToken, @RequestParam Long productId) {
        try {
            return ResponseEntity.ok().body(digitoonContentService.getProductsDetails(userToken, productId));
        } catch (InvalidTokenException e) {
            logger.info("token is null or invalid", e);
            MultiValueMap<String, String> headers = new HttpHeaders();
            headers.add("invalid_token", "true");
            ErrorDTO errorDTO = new ErrorDTO(HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED.value(), e.getMessage());
            return new ResponseEntity<Object>(errorDTO, headers, HttpStatus.UNAUTHORIZED);
        }

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多