jax-rscxfrs

Add query param at runtime when using CXF proxy client


So I'm using CXF-RS proxy feature to create reusable REST client that I will use in multiple applications. So I have an interface, something like that :

@Path("/hello")
public interface HelloService {

    @GET
    @Path("sayHello")
    String sayHello(@QueryParam("name") String name);
}

And I'm creating the client with :

JAXRSClientFactory.create(address, HelloService.class, Collections.singletonList(JacksonJsonProvider.class), true)

But now I need depending on the configuration of the application to send an additional query parameter to the request. I would like not to change the interface HelloService and instead use some kind of filter to handle this. I saw the ClientRequestFilter but I don't know if it's the right tool and how I should add it to the proxy (all the tutorials I saw use ClientBuilder.newClient() and not a proxy).

Thank you in advance.


Solution

  • Sure you can use a ClientRequestFilter for this. Say you wanted to add a query param. You could do something like

    public class MyClientFilter implements ClientRequestFilter {
    
        @Override
        public void filter(ClientRequestContext request) throws IOException {
            request.setUri(UriBuilder.fromUri(request.getUri())
                    .queryParam("foo", "bar")
                    .build());
        }
    }
    

    To register it, you just add it to the list you pass as the third argument to JAXRSClientFactory.create. Look at the docs for JAXRSClientFactory. You can see the overloaded create methods that accepts a list of providers. The ClientRequestFilter is a kind of provider.