Search code examples
quarkusresteasymicroprofile

Is it possible to get outbound client request information in ClientHeadersFactory?


I am writing an application with the following layers:

External Client (e.g. browser) -> My Service -> External API

I have a ClientHeadersFactory which adds some headers to the REST Client I use in My Service to call External API. I was wondering whether it was possible to get information about the client request from my REST Client in My Service to External API? For example, I'd like to know the HTTP method and the endpoint my REST Client is calling. This will impact what headers I add.

Thanks!


Solution

  • ClientHeadersFactory is not designed for use cases where looking into the request is necessary. To add headers based on the request, you can use ClientRequestFilter.

    Note, that you can mix ClientHeadersFactory with filters.

    For example, you could do something like this:

    import javax.ws.rs.client.ClientRequestContext;
    import javax.ws.rs.client.ClientRequestFilter;
    import java.io.IOException;
    
    public class MyFilter implements ClientRequestFilter {
        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            if ("POST".equalsIgnoreCase(requestContext.getMethod())) {
                requestContext.getHeaders().add("MyHeader", "POST-specific header");
            }
        }
    }
    
    

    You can register such a filter for a single client, by annotating the client with @RegisterProvider(MyFilter.class), or, if you use quarkus-rest-client-reactive, for all the clients in your application by adding the @Provider annotation to the filter.