向 Spring ResponseEntity 添加新的 Header

问题描述 投票:0回答:4

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

这是我的代码:

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

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

java.lang.UnsupportedOperationException

java spring http http-headers httpresponse
4个回答
3
投票

ResponseEntity.getHeaders() 返回不可变对象,因此如果您尝试更新它,您会得到

java.lang.UnsupportedOperationException

因此,您必须创建一个新的标头副本并填充现有标头,并在其顶部添加新的所需标头。最后将标头附加到 ResponseEntity。

 //create a new headers object.
    HttpHeaders headers = new HttpHeaders();
    //add all existing headers in new headers
     headers.addAll(response.getHeaders()); 
    //add the new required header
    headers.add("newheader","newvalue"); 
    //add the headers to the responseEntity along with yourBody object
    ResponseEntity.status(HttpStatus.OK).headers(headers).body(yourBody);

2
投票

您需要立即创建一个。

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

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);
        }

0
投票

您必须创建您的

ResponseEntity
的副本。不幸的是
HttpHeaders
是只读的。但是有一个有用的方法可以将只读
HttpHeaders
“转换”(如果 HttpHeaders 是只读的,它会生成一个副本)为可写
HttpHeaders
HttpHeaders.writableHttpHeaders(HttpHeaders headers)

public <T> ResponseEntity<T> addCustomHeader(ResponseEntity<T> response, String headerName, String headerValue) {
  HttpHeaders headers = HttpHeaders.writableHttpHeaders(response.getHeaders());
  headers.add(headerName, headerValue);
  return new ResponseEntity<>(response.getBody(), headers, response.getStatusCode());
}

© www.soinside.com 2019 - 2024. All rights reserved.