Wednesday, June 13, 2012

How to create a simple CXF based JAX-RS Client

 
In my previous blog post, I did explain how to create a REST API using CXF and Spring.

This time I would like to describe how to quickly create a client that can call the REST API while reusing the resources POJO classes,
so the un-marshalling is done by JAXB.

For this I am using the CXF WebClient which is very simple to use:

  • import WebClient from org.apache.cxf.jaxrs.client.WebClient
  • import your POJOs
  • import a JABX provider (I am using Jackson JAXB JSON provider)

 Here is a very simple standalone program that does exactly this (make sure your REST API has been deployed locally):
 
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.apache.cxf.jaxrs.client.WebClient;
import java.util.ArrayList;
import java.util.List;

public class App 
{
    public static void main( String[] args )  throws Exception { 
      
     List<Object> providers = new ArrayList<Object>();
     providers.add( new JacksonJaxbJsonProvider() );
   
     WebClient client = WebClient.create("http://localhost:8080/poc_restapi_cxf/api", providers);
     client = client.accept("application/json").type("application/json").path("/order").query("id", "1");
   
     Order order = client.get(Order.class);
     System.out.println("Order:" + order.getCustomerName());
  
    }
}
With this very simple client program, the response to your request (JSON) is automatically unmarshalled to a Java object. 

If you are using maven, make sure you have the correct dependencies in your pom file:
    <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-transports-http</artifactId>
       <version>${cxf.version}</version>
       <scope>provided</scope>
    </dependency>
   
    <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-rs-extension-search</artifactId>
       <version>${cxf.version}</version>
       <scope>provided</scope>
    </dependency>
     
    <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-rs-extension-providers</artifactId>
       <version>${cxf.version}</version>
       <scope>provided</scope>
    </dependency>
      
    <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
       <artifactId>jackson-jaxrs-json-provider</artifactId>
       <version>2.0.2</version>
    </dependency> 

No comments: