Home > database >  How can I propagate request headers to response headers in SpringBoot 2
How can I propagate request headers to response headers in SpringBoot 2

Time:05-31

I have interfaces generated by Swagger Codegen. It looks like this:

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

In the implementation I want to have a full list of request headers (I need some of them in the response) or to be able to get a value of a header that is not listed in the API. The thing is I cannot change the signature of the endpoint since it will cause a major headache in further releases. So is there any way to achieve this?

CodePudding user response:

You have the request object in your code already so you can get the headers from it. i.e. request.getHeaderNames() then loop through them.

After that, you can add them to the response with

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("key", "value");
ResponseEntity.ok().headers(responseHeaders).body("some body");
  • Related