0

I'm having multiple microservices

1. MangerApp 
2. ProcessApp
3. DoingStuffApp
4. .....

the "MangerApp Microservices" get an Http-Request I'm looking for a way to transfer automatically some of the HTTP headers in the call, while I don't want to go over each place and do - add Headers, my HTTP headers are stored as a thread-local Map.

since I call to other microservices, with RestTemplate I have many different calls some get/post/put/etc... changing each one them and passing the header manually is not that efficient. I'm looking for a way to manage it, other than extending the RestTemplate Class now.

Hard Worker
  • 995
  • 11
  • 33

1 Answers1

4

You can use a ClientHttpRequestInterceptor to achieve what you need.

1) Create a HeaderInterceptor implementing ClientHttpRequestInterceptor. In this example it gets the Authorization and Accept headers from a ThreadLocal and propagates them:

public class HeaderInterceptor implements ClientHttpRequestInterceptor{

    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

                    HttpHeaders headers = request.getHeaders();
        List<String> authorization = HeaderThreadLocal.getAuthorization()
        List<String> accept = HeaderThreadLocal.getAuthorization();

        headers.addAll("Authorization", authorization);
        headers.addAll("Accept", accept);
        return execution.execute(request, body);
    }
}

2) Configure your RestTemplate bean adding the header interceptor:

restTemplate.getInterceptors().add(new HeaderInterceptor());
codependent
  • 23,193
  • 31
  • 166
  • 308
  • Read about here https://www.baeldung.com/spring-rest-template-interceptor which says it will intercept for every incoming call. "Our interceptor will be invoked for every incoming request", what I need is to intercept for every outgoing call – Hard Worker Jun 14 '20 at 13:34
  • 1
    That’s what this implementation does. Baeldung’s article shows how to add a header to the response. My code adds it for the RestTemplate request, which is what you need. – codependent Jun 14 '20 at 13:51
  • I cant find the dependency for HeaderThreadLocal. Any help ? @codependent – zealvault Sep 22 '22 at 16:03