In a previous article, I showed you how to automatically add information when logging from a Java Spring application to Application Insights logs using the Mapped Diagnostic Context. The code for that article is here.

The example I used in that article generated a Request Key every time a controller method is calling. An alternative solution is to have the client that calls the controller pass the Request Key to method in the HTTP Header.

Request Headers

To read the Header of an HTTP request in a controller method, add a parameter of type HttpServletRequest.

An HTTP header can contain one or more key/value pairs. The HttpServletRequest object allows you to read the value of a given key, using the getHeader method and pasing in the key. If we add an HTTP Header with the key "X-Request-Key" to our request, we can retrieve it java with a line like:

String request requsestKey = request.getHeader("X-Request-Key");

The modified controller code looks like this:

@GetMapping("add/{firstNumber}/{secondNumber}")
public ResponseEntity<Integer> Add(
    @PathVariable("firstNumber") Integer firstNumber, 
    @PathVariable("secondNumber") Integer secondNumber,
    HttpServletRequest request) {
        String requestKey = request.getHeader("X-Request-Key");
        if (requestKey == null) {
            requestKey = UUID.randomUUID().toString();
        }
        MDC.put("Request-Key", requestKey);
        logger.info("MathController.Add() called with " + firstNumber + " and " + secondNumber);

        Integer sum = mathService.AddNumbers(firstNumber, secondNumber);
        return new ResponseEntity<Integer>(sum, HttpStatus.OK);
}

Using a tool like Postman, I can send an HTTP request and add a custom header to that request, as shown in Fig. 1.

Custom HTTP Request Header in Postman
Fig. 1

This works the same as the code in my previous article, except the calling client is given the opportunity to pass in the Request Key, rather than having the controller generate it.

Response Headers

An HTTP Response also contains Header information and we can write Java code to include custom key/value pairs in the Response Header.

The HTTPHeaders object (in the org.springframework.http namespace) allows you to write to the response header. This object has a set method that accepts a key and a value as parameters, so you can pass that back with the HTTP Response Headers.

Our existing code returned a ResponseEntity object, which has a constructor overload that allows us to include an HTTPHeaders object in the response.

Here is the updated code in the controller:

@GetMapping("add/{firstNumber}/{secondNumber}")
public ResponseEntity<Integer> Add(
    @PathVariable("firstNumber") Integer firstNumber, 
    @PathVariable("secondNumber") Integer secondNumber,
    HttpServletRequest request) {
        String requestKey = request.getHeader("X-Request-Key");
        if (requestKey == null) {
            requestKey = UUID.randomUUID().toString();
        }
        MDC.put("Request-Key", requestKey);
        logger.info("MathController.Add() called with " + firstNumber + " and " + secondNumber);

        Integer sum = mathService.AddNumbers(firstNumber, secondNumber);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("X-Request-Key", requestKey);
        return new ResponseEntity<Integer>(sum, responseHeaders, HttpStatus.OK);
}

Now, when we run the application and call this controller method, we not only get information in the body of the HTTP Response; we also receive the Request Key in the HTTP Response Header, as shown in Fig. 2.

Custom HTTP Response Header in Postman
Fig. 2

Conclusion

In this article, you learned how to read Header information from an HTTP Request and to write Header information to an HTTP Response, using Java code.

You can find the code for this article here.