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 = {
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);
        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?

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

Leave a Reply