如何在 Spring Boot 2 中将请求 headers 传播到响应 headers

How can I propagate request headers to response headers in SpringBoot 2

我有 Swagger Codegen 生成的接口。它看起来像这样:

@PostMapping(value = "/ipc/conf", produces = {"application/json", "application/problem+json"}, consumes = {
            "application/json"})
default ResponseEntity<CustomResponseEntity> ipcConfPost(
            @ApiParam(value = "ID", required = true) @RequestHeader(value = "X-Request-ID", required = true) String xRequestID,
            @ApiParam(value = "Value for identifying a single transaction across multiple services up to the backend.", required = true) @RequestHeader(value = "X-Correlation-ID", required = true) String xCorrelationID,
            @ApiParam(value = "The payload to transmit", required = true) @Valid @RequestBody IPcData ipcConfData,
            @ApiParam(value = "The business context is a general classification for a larger number of requests.") @RequestHeader(value = "X-Business-Context", required = false) String xBusinessContext) {
        getRequest().ifPresent(request -> {
            for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
                if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
                    String exampleString = "{ \"id\" : \"id\", \"error\" : \"error\" }";
                    ApiUtil.setExampleResponse(request, "application/json", exampleString);
                    break;
                }
            }
        });
        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
    }

在实现中,我想要一个完整的请求列表 header(我需要其中的一些在响应中)或者能够获得一个 header 的值,即未在 API 中列出。问题是我 不能 更改端点的签名,因为它会在以后的版本中引起严重的麻烦。 那么有什么办法可以实现吗?

您的代码中已经有请求 object,因此您可以从中获取 headers。即 request.getHeaderNames() 然后遍历它们。

之后,您可以使用

将它们添加到响应中
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("key", "value");
ResponseEntity.ok().headers(responseHeaders).body("some body");