Implementing client-side request message filters

JAX-RS lets you build a client-side request filter for REST API calls by implementing the javax.ws.rs.client.ClientRequestFilter interface. This filter is used for intercepting the REST API calls on the client itself.

A very common use case scenario where you may find these filters useful is for checking the accuracy of specific request parameters on the client itself. Even you can abort the call and return the error response object from these filters if the request parameter values are not properly specified.

The following code snippet illustrates how you can use ClientRequestFilter to ensure that all the requests carry the Client-Application header field, which you may use on the server for tracking all clients:

//Other imports are omitted for brevity 
import javax.ws.rs.HttpMethod; 
import javax.ws.rs.client.ClientRequestContext; 
import javax.ws.rs.client.ClientRequestFilter;  
 
@Provider 
public class JAXRSClientRequestFilter implements 
    ClientRequestFilter { 
  
    @Override 
    public void filter(ClientRequestContext requestContext) 
        throws IOException { 
        if(requestContext.getHeaders() 
           .get("Client-Application") == null) { 
                requestContext.abortWith( 
                    Response.status(Response.Status.BAD_REQUEST) 
                        .entity( 
                           "Client-Application header is 
required.") .build()); } } }

You can register the ClientRequestFilter interface to the client by calling the register() method on the javax.ws.rs.client.Client object. Note that the client object implements the javax.ws.rs.core.Configurable interface, and all the configurations that you see on Client are offered by the Configurable interface. The following code snippet shows how you can add JAXRSClientRequestFilter to the JAX-RS client implementation:

import javax.ws.rs.client.Client; 
import javax.ws.rs.client.ClientBuilder; 
 
Client client = ClientBuilder.newClient(); 
client.register(JSXRSClientRequestFilter.class);  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.156.235