Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading