【问题标题】:Add a new Header to Spring ResponseEntity向 Spring ResponseEntity 添加一个新的 Header
【发布时间】:2018-01-29 05:53:50
【问题描述】:

如何向 org.springframework.http.ResponseEntity 对象添加新标头?

这是我的代码:

public void addCustomHeader(ResponseEntity response,String headerName,String headerValue)
{
  response.getHeaders().add(headerName, headerValue);
}

当我尝试上面的代码时,我得到了

java.lang.UnsupportedOperationException

【问题讨论】:

  • ResponseEntity 是不可变的,您必须创建一个新的。

标签: java spring http http-headers httpresponse


【解决方案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);
        }

【讨论】:

    【解决方案2】:

    你需要现在创建一个。

       final HttpHeaders responseHeaders = new HttpHeaders();
       responseHeaders.set(headerName, headerValue);
       final ResponseEntity<> response = new ResponseEntity<>(responseHeaders, HttpStatus.FORBIDDEN);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-25
      • 2017-07-28
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2022-10-22
      • 2014-01-09
      相关资源
      最近更新 更多